2

I'm trying to iterate over a Python list and delete each element once I've done some tasks with it, but it jumps one element after each iteration and I don't know why:

>>> simple_list = list(range(10))
>>> simple_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> for i in simple_list:
...     print(i)
...     simple_list.remove(i)
... 
0
2
4
6
8

>>> simple_list
[1, 3, 5, 7, 9]

Does anyone know why this is happening? Only the even elements are being removed, and looks like the loop doesn't go through the uneven ones.

Xoel
  • 318
  • 4
  • 15

4 Answers4

2

Well, your list is shrinking while you are iterating over it. If you want to, just look at the first element while your iterate over it.

while len(simple_list) > 0:
    print(simple_list[0])
    del simple_list[0]
Spinor8
  • 1,587
  • 4
  • 21
  • 48
1

You can use list comprehension to get copy of the array and then iterate.

simple_list = list(range(10))
for i in simple_list[:]:
    print(i)
    simple_list.remove(i)
dhilmathy
  • 2,800
  • 2
  • 21
  • 29
1

Or this:

for i in simple_list[:]:
   simple_list.remove(i)
print(simple_list)

Output:

[]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

Ok, found the answer here: Python: Removing list element while iterating over list

You should NEVER delete an element from a list while iterating over it in a for loop. You could use a while loop instead. Or, record the indices of all the elements you want to remove and then delete them after the iteration is complete

Xoel
  • 318
  • 4
  • 15