Negative indexing for lists (and other sequences)

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 more elegant than the clunky equivalent of computing a positive index, which you would otherwise need to use for retrieving that last element:

>>> r[len(r) - 1]

Note that indexing with -0 is the same as indexing with 0 and returns the first element in the list. Because there is no distinction between 0 and negative zero, negative indexing is essentially one-based rather than zero-based. This is good to keep in mind if you're calculating indices with even moderately complex logic: One-off errors can creep into negative indexing fairly easily.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset