[Tutor] IndexError: string index out of range
Lloyd Kvam
pythonTutor at venix.com
Tue Nov 2 15:33:31 CET 2004
Somewhat nit-picking but it is really
while -len(fruit) <= index < len(fruit): # valid index values
On Tue, 2004-11-02 at 09:03, Dragonfirebane at aol.com wrote:
> >>>>index = -1
> >>>>while index < len(fruit):
> >>>>
> >>>>
> >... print [index], '\t', fruit[index]
> >... index = index - 1
> >...
> >[-1] a
> >[-2] n
> >[-3] a
> >[-4] n
> >[-5] a
> >[-6] b
> >[-7] Traceback (most recent call last):
> > File "<stdin>", line 2, in ?
> >IndexError: string index out of range
>
> len(fruit) is positive and index is negative, so index will always be
> smaller than len(fruit) . . . you want
>
> >>> index = -1
> >>> while abs(index) <= len(fruit):
> print [index], '\t', fruit[index]
> index -= 1
>
> [-1] a
> [-2] n
> [-3] a
> [-4] n
> [-5] a
> [-6] b
>
> that way, you're comparing the absolute value of index with the length
> of fruit and the loop will end w/o reaching an error
>
>
> Email: dragonfirebane at aol.com
> AIM: singingxduck
> Programming Python for the fun of it.
>
> ______________________________________________________________________
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list