-1

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 = ["A", "B", "C", "D", "E", "F", "G", ]


for i in range(len(myList)):

    if i == 2:
        del (myList[4])

    print(i, myList[i])

--------------------------Run-------------------------------------------------

"C:\Python36\python.exe" 

Traceback (most recent call last):

0 A
  File "C:/Users/reading.py", line 10, in <module>

1 B

2 C

    print(i, myList[i])
3 D

4 F

IndexError: list index out of range

5 G

Process finished with exit code 1
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
WannaLaugh
  • 23
  • 1
  • 3

4 Answers4

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.

yanxun
  • 566
  • 2
  • 10
0

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.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

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
`
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
chihoxtra
  • 31
  • 2
0

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']
srikavineehari
  • 2,502
  • 1
  • 11
  • 21