Daniel Lemire's blog

, 4 min read

Python allows negative indexing on arrays!

6 thoughts on “Python allows negative indexing on arrays!”

  1. (Clever anonymous poster above was in BC when he posted this message. At least from the IP to location tool I used.)

  2. didier says:

    Perl uses negative indexing too.

  3. Toby says:

    An empty list raises an index exception if you try to access any location. And, yes, if there is only 1 element, then lst[0] and lst[-1] refer to the same value.

    Basically, Python’s sequence indexing gives each element two indices: a negative one and a non-negative one, i.e. i and i – n (where n is the length of the list).

    Most of the time I (and I think most other Python programmers) use the regular C-like index notation, and every once in a while use the negative index notation, mostly for accessing the last element or two of a sequence And even then, it’s usually a literal index, i.e. lst[-1] or lst[[-2], and almost never with variables, e.g.:

    >>> lst = [6, 5, 3, 2]
    >>> for i in range(len(lst)): # print lst in reverse
    … print lst[-i – 1]

    2
    3
    5
    6

  4. Anonymous says:

    Negative indexing makes it easy to access the end of a list, e.g. you can write lst[-1] instead of lst[len(lst) – 1].

    It can also be used with slicing, e.g. filename[-3:] gives you the extension of the file name.

  5. brem says:

    What happens when the array is empty?

    and if there is only 1 element, does [0] and [-1] points to the same element?

  6. brem says:

    Thanks for the precisions. 🙂