3.1.4.5 Lists - collections of data | Operations on lists
Negative indices are legal
It may look strange, but negative indices are legal, and can be very useful.
An element with an index equal to
-1 is the last one in the list.print(numbers[-1])
The example snippet will output
1. Run the program and check.
Similarly, the element with an index equal to
-2 is the one before last in the list.print(numbers[-2])
The example snippet will output
2.
The last accessible element in our list is
numbers[-4] (the first one) - don't try to go any further!
Comments
Post a Comment