simple beginner question about lists and negative index

dwblas at gmail.com dwblas at gmail.com
Sat May 3 13:55:59 EDT 2008


On May 1, 10:04 am, "Terry Reedy" <tjre... at udel.edu> wrote:
> "jmDesktop" <needin4mat... at gmail.com> wrote in message
> |
> | s = 'abcde'
> | i = -1
> | for i in range (-1, -len(s), -1):
> |    print s[:i], i
> | Why doesn't the first one have the e if -1 is the end of the list?

That should be obvious.  'print s[-1]' will yield the "e", but your
code is using slicing, s[:i], not printing elements from a list.  Your
code starts with the value s[:-1], which is exactly the same as
s[0:-1], so you print the string from 0 to -1 which omits the last
letter.  The next time it omits the last 2 letters s[:-2].  As already
stated, that should be very obvious.  Also, if you want a response in
the future, make your code readable.  That means not using, "i", "l",
or "o" as variable names.  They look too much like numbers and some
people won't waste their time trying to distinguish between them.
There are 23 other letters that work just a well.



More information about the Python-list mailing list