Tuesday, November 27, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...