How to avoid “IndexError: list index out of range” error in my Python code

后端 未结 4 741
陌清茗
陌清茗 2021-01-29 05:45

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.

相关标签:
4条回答
  • 2021-01-29 06:19

    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.

    0 讨论(0)
  • 2021-01-29 06:19

    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
    `
    
    0 讨论(0)
  • 2021-01-29 06:23

    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.

    0 讨论(0)
  • 2021-01-29 06:29

    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']
    
    0 讨论(0)
提交回复
热议问题