# negative indices for sequence types

Erik Max Francis max at alcyone.com
Sun Sep 7 22:01:11 CEST 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).

That is not the behavior of negative indices.  Negative indices mean
index from the end of the sequence.  So -1 means the _last_ element in
the list, -2 means the second to last element in the list, and so on.
-n (for n = len(seq) is the first element in the list.

> This fact is *deeply* buried in the docs, and is not at all intuitive.

It's mentioned prominently (and early) in all the tutorials and books on
Python I've read, and it's a very common and convenient convention, so
I'm not sure how far you could have gotten through learning Python and
never been exposed to it.

>  One of the big advantages of a high-level language such as Python is
> the ability to provide run-time bounds checking on array-type
> constructs.  To achieve this I will now have to subclass my objects
> and add it myself, which seems silly and will add significant
> overhead.  If you want this behavior, how hard is it to say a = b[x %
> len(b)] ??

That's simply not true.  Negative indices have similar bounds
requirements.  If you have a sequence of length n, then indices 0
through (n - 1) map to the elements of the sequence in order from left
to right, and indices -1 through -n map to the elements in order from
right to left.  Indices greater than n or less than -n generate
IndexErrors.  Bounds checking is always done, whether on positive or
negative indices.

--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Then you give me that Judas Kiss / Could you hurt me more than this
\__/  Lamya

```