negative indices for sequence types

Terry Reedy tjreedy at
Sun Sep 7 21:31:34 CEST 2003

"dan" <danbmil99 at> wrote in message
news:fbf8d8f2.0309071026.4c44b985 at
> 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).

No, it adds len(seq).  Changing + to % would be slower and more

> This fact is *deeply* buried in the docs,

No more so than everything else in chapter subsections.  From the Ref
Man table of contents I went directly to the most obvious place 5.3.2
Subscriptions, and found
If the primary is a sequence, the expression (list) must evaluate to a
plain integer. If this value is negative, the length of the sequence
is added to it (so that, e.g., x[-1] selects the last item of x.) The
resulting value must be a nonnegative integer less than the number of
items in the sequence, and the subscription selects the item whose
index is that value (counting from zero).
Translated to Python, letting idex be result of index expression:

if not isinstance(idex, (int,long)): raise TypeError()
if idex < 0: idex += seqlen
if idex < 0 or idex >= seqlen: raise IndexError()
<get seq[idex]>

> and is not at all intuitive.

Phrases like 'third from the end' are idiomatic English ;-)

>  One of the big advantages of a high-level language such as Python
> 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)] ??

Again, your innovation of using '% obscures rather than clarify.

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

Being able to abbreviate seq(len(seq)-1] as seq[-1] is quite handy and
faster executing, , especially if seq is calculated from an
expression.  Same for -2, etc.  (And, of course, a change now would
break a noticeable fraction of existing programs.)

Terry J. Reedy

More information about the Python-list mailing list