[Tutor] IndexError: list index out of range

James Reynolds eire1130 at gmail.com
Mon Nov 21 18:43:30 CET 2011


On Tue, Nov 22, 2011 at 12:28 AM, John <nidianjs at hotmail.com> 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])
>
>
>
> 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?
>
> Big thanks,
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>


I don't really know what it is you are trying to achieve, but I can tell
you this, if you add a print statement you can see very clearly why you are
getting the error:

def survivor(names, step):
    index = step - 1
    next = names
    while len(next)>  1:
        print next, index
        next.remove (next[index])
survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
"Felicity", "Greg", "Harriet"], 4)


['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg',
'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig'] 3
Traceback (most recent call last):
  File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 40,
in <module>
    "Felicity", "Greg", "Harriet"], 4)
  File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 38,
in survivor
    next.remove (next[index])
IndexError: list index out of range


As you can see in this line: ['Andrew', 'Brenda', 'Craig'] 3

It looks for index "3" and there isn't one, so it throws an error. The
indexes available are 0,1 and 2.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111121/db162d73/attachment.html>


More information about the Tutor mailing list