-3

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?

Sid
  • 2,174
  • 1
  • 13
  • 29

1 Answers1

2

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.

nmpauls
  • 144
  • 1
  • 9