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

后端 未结 4 788
陌清茗
陌清茗 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: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']
    

提交回复
热议问题