[Tutor] IndexError: list index out of range

Steven D'Aprano steve at pearwood.info
Tue Nov 22 00:02:01 CET 2011

John wrote:
> Hi all,
> I have wriiten the following code:
> [Segment]
>>>>  def survivor(names, step):
>     index = step - 1
>     next = names
>     while len(next)>  1:
>         next.remove (next[index])

What is the intention of this function? The name given doesn't mean 
anything to me. The parameters "names" and "step" don't seem meaningful.

I can see what the function does: it deletes bits of something, probably 
a list, in a convoluted way, eventually causing an error. But I can't 
tell what it is *supposed* to do.

Given the example you show later on:

survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
     "Felicity", "Greg", "Harriet"], 4)

what should the result be?

> However when ever i run it i get this error message:
> Traceback (most recent call last):
>   File "<pyshell#46>", line 1, in<module>
>     survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
> "Felicity", "Greg", "Harriet"], 4)
>   File "<pyshell#45>", line 5, in survivor
>     next.remove (next[index])
> IndexError: list index out of range
> Any ideas about whats causing this error?

You attempt to delete an item that doesn't exist.


More information about the Tutor mailing list