We've already covered lists a little, and we've been making good use of them. We know how to create lists using the literal syntax, add to them using the append()
method, and get at and modify their contents using the square brackets indexing with positive, zero-based indexes.
Zero and positive integers index from the front of a list, so index four is the fifth element in the list:
Figure 5.5: Zero and positive integers index
Now we'll take a deeper look.
One very convenient feature of lists (and other Python sequences, for this applies to tuples too) is the ability to index from the end, rather than from the beginning. This is achieved by supplying negative indices. For example:
>>> r = [1, -4, 10, -16, 15] >>> r[-1] 15 >>> r[-2] -16
Negative integers are −1 based backwards from the end, so index −5 is the last but fourth element as shown in the following diagram:
Figure 5.6: Reverse index
This is much...