Tuesday 27 November 2018

Why does calling [-1] of a python list give this output?





This may be a theoretical question, but please bear with me. Why does this Python code produce this output?



content = ['abc', 'def', 'ghi', 'jkl', '\n.']
print(content[-1])



The output is:




.


Why does the . come? Why isn't there an error?


Answer



Python lists can be indexed by negative numbers, with -1 referring to the last element, -2 referring to the second to last element, and so on.




Specifically for this example, content[-1] refers to '\n.'. The character '\n' is a whitespace character that creates a new line. Thus, your print statement outputs a new line followed by the period.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...