[Tutor] IndexError: string index out of range

Michael Janssen mi.janssen at gmail.com
Tue Nov 2 14:06:19 CET 2004


On Tue, 02 Nov 2004 15:18:15 +0300, Eri Mendz <jerimed at myrealbox.com> wrote:

> I'm geting IndexError when iterating over a string in reverse. What
> exactly does this mean? help(IndexError) in the interpreter isnt very
> helpful.

> >>> fruit = 'banana'
> >>> index = 0
> >>> while index < len(fruit):
> ...     print [index], '\t', fruit[index]
> ...     index = index + 1
> ...
> [0]     b
> [1]     a
> [2]     n
> [3]     a
> [4]     n
> [5]     a
> >>>
> >>> 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

This means: string index "banana"[-7] is out of range. Quite obviously ;-)

Perhaps you're confused why the loopcondition "while indey >
len(fruit)" was fine in the former example but lends to an IndexError
with the second example.

Reason is that you *decrement* index in the second example and thus
index will be smaller than len(fruit) until the end of time. index
will be decremented without boundaries. Without the IndexError, you
would while loop forever ("for a long time"). Your while condition
should have read "while index >= -1 * len(fruits)", which would
terminate when index = -7  which is smaller than -1 * 6.

These handmade indexing is allways hard to code. Better to use a for-loop:

for char in fruit:
    print char

for index,char in enumerate(fruit):
    print [index], char

(but while this is fine coding style, it's not such a challenging
learning example ;-)


Things like IndexError are described in lib/module-exceptions.html
(when you want to know relationship and generall usage).

Michael


More information about the Tutor mailing list