negative indices for sequence types

Fernando Perez fperez528 at yahoo.com
Mon Sep 8 02:55:06 EDT 2003


dan wrote:

> I was recently surprised, and quite shocked in fact, to find that
> Python treats negative indices into sequence types as if they were
> mod(length-of-sequence), at least up to -len(seq).
> 
> This fact is *deeply* buried in the docs, and is not at all intuitive.

Very deeply indeed: section 3.1.4 of the beginner's tutorial:

http://www.python.org/doc/current/tut/node5.html#SECTION005140000000000000000

Of all places, this is the section on lists:

>>> a = ['spam', 'eggs', 100, 1234]

        [... snip ...]

>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]

> Can anyone explain why this anomaly exists, and why it should continue
> to exist?

Because this 'anomaly' is incredibly useful in many contexts, as many others
have already pointed out.  Rest assured that it will continue to exist,
probably for as long as the language is around.  Better get to like it :)

Cheers,

f.




More information about the Python-list mailing list