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

Anonymoussays:

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.

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

didiersays:Perl uses negative indexing too.

Tobysays: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

Anonymoussays: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.

bremsays:What happens when the array is empty?

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

bremsays:Thanks for the precisions. 🙂