negative indices for sequence types

Peter Otten __peter__ at web.de
Sun Sep 7 15:02:55 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.
>  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)] ??
> 
> Can anyone explain why this anomaly exists, and why it should continue
> to exist?

After you have recovered from the shock, you probably will admit that 
(1) the most common "out of bounds" case is caught:

>>> l = list("abc")
>>> l[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range

and 
(2) that accessing elements from the end of the list is something you will
soon appreciate:
>>> l[-1]
'c'
>>>

>>> l[-2:]
['b', 'c']
>>>

I think that more code enjoys the beauty of accessing the end of a list than
suffers from uncaught <0 index errors. See the possibilities rather than
the danger :-)

Peter





More information about the Python-list mailing list