"list index out of range" error

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Sep 20 17:54:49 EDT 2006


In <1158787569.955853.223030 at h48g2000cwc.googlegroups.com>, sam wrote:

> i'm trying to code a version of a selection sort and the heart of the
> code is as follows (no_lines is simply the number of items to be
> sorted, read out of an input file):
> 
> for j in range(0, no_lines):
> 
>     k = 0
>     while k < no_lines:
>         sorted_check = 0
>         if list_initial[k] < list_initial[k+1]:
>             temp_str = list_initial[k]
>         elif list_initial[k] == list_initial[k+1]:
>             temp_str = list_initial[k]
>         elif list_initial[k] > list_initial[k+1]:
>             temp_str = list_initial[k+1]
>             sorted_check = 1
>         k += 1
> 
>     list_initial.remove(temp_str)
>     list_final.append(temp_str)
>     no_lines -= 1
> 
>     if sorted_check == 0:
>         break
> 
> problem is, i keep getting a "list index out of range" error. i've had
> this problem before in different contexts with lists in loops.
> 
> i thought i had it cracked when it occurred to me that i needed to
> decrement no_lines to take into account that list_initial was shrinking
> as i deleted sorted items, but i still got the same error. it's
> probably something trivial, but i can't seem to get round it by using
> while loops, and i had the same problem with cmp(), hence the explicit
> comparison above, which still doesn't work. can anyone help a beginner
> out with this?

It has nothing to do with `cmp()` vs. explicit testing but with indexing
the `k+1` element.  Let's assume `no_lines` is 10 then the elements have
the indexes 0 to 9.  Within the while loop `k` is incremented and the loop
body is executed as long as `k < 10`.  When `k == 9` you try to access the
element at index `k+1`, but there is no element at index 10.  So you get
the `IndexError`.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list