Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
I'm wondering how to format my "for loop" so it applies to any list of numbers inputted and so I don't get this error: "IndexError: list index out of range" and also .
I'm having a hard time understanding when to use what in my loops (i.e. for x in range(value) vs for x in value), or when to use while loops, etc. Are there any detailed guides on this somewhere? i have 3 books and I've searched the internet, but haven't found anything that's both understandable and goes into greater detail.
Here is my code, it calculates what I want (New = 2, 3), but I get the error at the end and I'm not sure how to fix it.
values = [2, 2, 3, 3, 3]
numbers = values.copy()
for x in range(len(numbers)):
while numbers[x] == numbers[x-1]:
del numbers[x]
print(f"Original = {values}")
print(f"New = {numbers}")
This is the output for my code:
Original = [2, 2, 3, 3, 3]
New = [2, 3, 3, 3]
Original = [2, 2, 3, 3, 3]
New = [2, 3, 3]
Original = [2, 2, 3, 3, 3]
New = [2, 3]
Traceback (most recent call last):
while numbers[x] == numbers[x-1]:
IndexError: list index out of rangepython - Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items? - Stack Overflow
Newbie Issue: "IndexError: list index out of range"
'List index out of range' when it is not.
list index out of range. i need help !
Videos
If you have a list with 53 items, the last one is thelist[52] because indexing starts at 0.
From Real Python: Understanding the Python Traceback - IndexError:
IndexErrorThe
IndexErroris raised when you attempt to retrieve an index from a sequence, like alistor atuple, and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:Raised when a sequence subscript is out of range. (Source)
Here’s an example that raises the
IndexError:
test = list(range(53))
test[53]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
1 test = list(range(53))
----> 2 test[53]
IndexError: list index out of range
The error message line for an
IndexErrordoesn’t give you great information. You can see that you have a sequence reference that isout of rangeand what the type of the sequence is, alistin this case. That information, combined with the rest of the traceback, is usually enough to help you quickly identify how to fix the issue.
Yes,
You are trying to access an element of the list that does not exist.
MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
Have you got an off-by-one error?