1

New to python - don't understand why the following seems to skip x=2 ?

a = [1, 2, 3]

for x in a:
    print("x=", x)
    print("a=", a)
    a.remove(x)
    print("new a=", a)

returns:

x= 1
a= [1, 2, 3]
new a= [2, 3]
x= 3
a= [2, 3]
new a= [2]

Process finished with exit code 0
norwegian
  • 13
  • 2
  • In general: if you mutate a sequence while iterating over it, the effects are usually somewhat undefined and/or unexpected. – deceze Sep 20 '17 at 13:57
  • It's because the loop walks through the indices not the values and I see that is a bug in conception – Abr001am Sep 20 '17 at 14:02
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – wwii Sep 20 '17 at 14:09

2 Answers2

0

You're changing the list as you iterate over it.

On its first loop, it's looking at the first element of a. Then you remove the first element, changing a to [2,3]. On its second loop, its looking at the second element of a. Because a has changed, its second element is now 3, which is what you get.

Andrew Hows
  • 1,429
  • 10
  • 16
0

The for loop is iterating over the memory location of the list a. After you delete the first element in the list. The second element is stored in the memory location of the first. Thus the loop loops over the second memory location next which currently is storing the third element.

Sumit
  • 486
  • 4
  • 16