"list index out of range" error

Tuomas tuomas.vesterinen at pp.inet.fi
Thu Sep 21 02:22:15 CEST 2006


sam wrote:

I gues: no_lines=len(list_initial)

> for j in range(0, no_lines):

   range returns 0, 1, 2, ..., no_lines-1

> 
>     k = 0
>     while k < no_lines:
>         sorted_check = 0
>         if list_initial[k] < list_initial[k+1]:

When j gets its last value (no_lines-1) k has the same value and k+1 
owerflows the list index range.

Try

   for j in range(1, no_lines):
       ...
           if list_initial[k-1] < list_initial[k]:
       ...

Tuomas

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



More information about the Python-list mailing list