Python Forum
index of range, but data prints out - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: index of range, but data prints out (/thread-33056.html)



index of range, but data prints out - mrc06405j - Mar-25-2021

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


RE: index of range, but data prints out - buran - Mar-25-2021

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