negative indices for sequence types

dan danbmil99 at yahoo.com
Mon Sep 8 13:11:26 EDT 2003


As is often the case, I think this comes down to documentation.  While
the behavior is mentioned early in the tutorial, I found it difficult
to find it in the reference -- but whatever, we can chalk this up to
RTFM on my part.

My explanation of the behavior is correct however.  list[a] always
equals list[a % len(list)].  A negative number mod N = its absolute
value subtracted from N:

a % n == n - abs(a) # where -n <= a <= 0

However if I want to count from the end of the list, I would of course
write
list[len(list)-a].  I wasn't really considering that the purpose of
this feature was to count from the end of a list, which I admit could
come in handy.

Thanks for the responses.

Fernando Perez <fperez528 at yahoo.com> wrote in message news:<bjh94c$j9p$1 at peabody.colorado.edu>...
> 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