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

后端 未结 4 781
陌清茗
陌清茗 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.

提交回复
热议问题