0
l = [10,10,10,10]

for x in l:
    l.remove(x)

print(l)

Im getting the output as [10,10]

But not able to understand why

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206

1 Answers1

0
l = [1, 2, 3, 4]

for i,e in enumerate(l):
    l.remove(e)
    print(i)

print(l)

Output: [2, 4]

First iteration, frst element is removing, then the list is [2, 3, 4]. Second iteration, you remove the second element of the new list ([2, 3, 4]), so you remove the 3, and 4 become the 2nd element. After that, you can't remove the third element because it does'nt exist.

If you run my code, you'll see that only 2 iterations are done.

If you want to delete items without modify index of the next, you can start by the end of the list as above.

l = [1, 2, 3, 4]

for i in range(len(l) - 1, - 1, -1):
    l.remove(l[i])
    print(i)

print(l)

This time the loop is running 4 times and the final list is empty.

Berni
  • 36
  • 6