Skip to content Skip to sidebar Skip to footer

How To Avoid "IndexError: List Index Out Of Range" Error In My Python Code

What is the best way to fix the error given in the run? I also somewhat understand that a list cannot change while being iterated over, but it still seems a little abstract. myList

Solution 1:

On the contrary, a list in Python can be changed (it is mutable), which is what you just did here:

del (myList[4])

In the beginning of the loop, len(myList) resolves to 6. At the final loop, where i = 6,

print(i, myList[i])

is essentially

print(i, myList[6])

However since you shortened it to 5, Python raises the out of range error.


Solution 2:

This is what list.pop is for!

myList = ["A", "B", "C", "D", "E", "F", "G"]

and remove the second element with:

myList.pop(2)

which will modify the list to:

['A', 'B', 'D', 'E', 'F', 'G']

As pointed out in the comments, modifying a list that you are iterating over is never a good idea. If something more complicated but similar to this had to be done, you would make a copy of the list first with myList[:] and then iterate through changing the copy. But for this scenario, list.pop is the definitely the right option.


Solution 3:

How about with:

myList = ["A", "B", "C", "D", "E", "F", "G"]

doing:

for i in range(len(myList)):
    if i == 2:
        del (myList[4])
    try:
        print(i, myList[i])
    except IndexError:
        None
`

Solution 4:

Try this:

myList = ["A", "B", "C", "D", "E", "F", "G"]

for i in range(len(myList)-4):
    if i == 2:
        del myList[4]
    print(i, myList[i])

0 A
1 B
2 C
>>> myList
['A', 'B', 'C', 'D', 'F', 'G']

Post a Comment for "How To Avoid "IndexError: List Index Out Of Range" Error In My Python Code"