Python Forum

Full Version: index of range, but data prints out
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have written a program in python. It occasionally gives an index out of range at a particular line in the code. I printed out all of the variables referenced in the offending line and they all printed out fine. I am thoroughly confused. How can all the indexed variables print out in one line and then raise an error in the next.

Can you offer any help in debugging this problem?

Thanks,
Michael

PS - I am happy to give you the code and any other information that might be helpful
>>> spam = [1, 2] # name spam refers to list
>>> spam
[1, 2]
>>> spam[2] # max index is 1, so this will raise error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> spam
[1, 2]
Basically your variable is some container type that can be access by index, like list, tuple, etc. But you try to access element by index that does not exists (i.e. it has less elements than you think). Note in python indexes start at 0.