negative indices for sequence types

Bengt Richter bokr at oz.net
Sun Sep 7 15:18:52 EDT 2003


On 7 Sep 2003 11:26:28 -0700, danbmil99 at yahoo.com (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)] ??

That isn't really the exact behavior. E.g.,

 >>> range(5)
 [0, 1, 2, 3, 4]
 >>> range(5)[-4]
 1
 >>> range(5)[-5]
 0
 >>> range(5)[-6]
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 IndexError: list index out of range

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

>Can anyone explain why this anomaly exists, and why it should continue
>to exist?
It has apparently proven more useful to have it so than not, though I sympathize
with your frustration in for your use.

Perhaps a .no_negative_indexing attribute or something could be added to the C implementation,
so that you could specify your desired checking without a performance hit.

Meanwhile, maybe an assert i>=0 in the index-supplier side of the contract might work too?

Regards,
Bengt Richter




More information about the Python-list mailing list