0

I understand that modifying a list while iterating over it can spell disaster. I was curious so I tried it anyway. In the first few examples below, things go as expected; but then something unusual happens in the second to last example.

>>> A = [0, 0, 0, 0]
>>> for k in A:
        if k == 0:
            A.remove(k)
>>> A
[0, 0]


>>> A = [0, 0, 0, 0, 1]
>>> for k in A:
        if k == 0:
            A.remove(k)
>>> A
[0, 0, 1]


>>> A = [0, 0, 0, 0, 1, 1]
>>> for k in A:
        if k == 0:
            A.remove(k)
>>> A
[0, 0, 1, 1]


>>> A = [0, 0, 0, 0, 1, 1, 0]  # Why does the presence of a fifth zero (the one at the end), cause an earlier zero to be removed?
>>> for k in A:
        if k == 0:
            A.remove(k)
>>> A
[0, 1, 1, 0]


>>> A = [0, 0, 0, 0, 1, 1, 2]
>>> for k in A:
        if k == 0:
            A.remove(k)
>>> A
[0, 0, 1, 1, 2]
tripleee
  • 175,061
  • 34
  • 275
  • 318
AndJM
  • 151
  • 1
  • 6

2 Answers2

0

I am not a Python expert, but just when I imagine how foreach loop is implemented:

len = size(array)
for i in range(0, len):
   loop_body(array[i])

Then for the second example:

len = 5, array=[0, 0, 0, 0, 1]

First iteration: i=0, array=[0, 0, 0, 0, 1], zero in array[0] is removed.

Second iteration: i=1, array=[0, 0, 0, 1], zero in array[1] is removed.

Third iteration: i=2, array=[0, 0, 1], array[2] == 1, nothing happened.

And this is your result. The same for the last one.

0

The remove method removes the first occurrence of x (I knew that, but forgot about it completely!) So when I execute this code:

>>> A = [0, 0, 0, 0, 1, 1, 0]
>>> for k in A:
        if k == 0:
            A.remove(k)

the presence of the zero at the end causes the zero in front of it (the one that was skipped over while iterating) to be removed. This produces:

>>> A
[0, 1, 1, 0]

I expected:

>>> A
[0, 0, 1, 1, 0]
AndJM
  • 151
  • 1
  • 6