[Tutor] IndexError: string index out of range

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 2 23:20:21 CET 2004



On Tue, 2 Nov 2004, Eri Mendz wrote:

> I understand slicing of strings, lists and tuples but a bit confused
> with indexing. Kindly enlighten me on this part. Fortunately i have the
> online tutorials printed out for reference but i agree the best way to
> learn is to practice and practice coding.

Hi Eri,


And make sure you're talking to other folks who are programming too ---
many of us can offer good advice about the kind of conventions that books
sometimes forget to mention... *grin*

There are still some programming pitfalls out there, even with the best of
tutorials, so it's invaluable that you talk to a group like this
Python-Tutor mailing list.



> >>> 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


People have already given reasons why this is sending out an IndexError,
so I'll try to avoid repeating them.

But another useful technique, when debugging something like this, is to
ask ourselves: what did we expect to happen instead?  By getting those
assumptions out there in the open, we might be able to figure out what was
causing the confusion.


For example, maybe we might have wanted it to continue cycling over and
over, like:

###
[-1]    a
[-2]    n
[-3]    a
[-4]    n
[-5]    a
[-6]    b
[-7]    a
[-8]    n
[-9]    a
[-10]    n
...
###

Or maybe we wanted something else.  It's really a good technique to try to
show what the expected result should be, since we can then start asking
questions like, "Why didn't it do *this* at this point, instead?"


Best of wishes to you!



More information about the Tutor mailing list