Reputation: 163
listA = [1,2,3]
listB = []
print listA
print listB
for i in listA:
if i >= 2:
listB.append(i)
listA.remove(i)
print listA
print listB
Why does this only add and remove element "2"?
Also, when I comment out "listA.remove(i)", it works as expected.
Upvotes: 7
Views: 6726
Reputation: 95298
You should not modify the list you are iterating over, this results in surprising behaviour (because the iterator uses indices internally and those are changed by removing elements). What you can do is to iterate over a copy of listA
:
for i in listA[:]:
if i >= 2:
listB.append(i)
listA.remove(i)
Example:
>>> listA = [1,2,3]
>>> listB = []
>>> for i in listA[:]:
... if i >= 2:
... listB.append(i)
... listA.remove(i)
...
>>> listA
[1]
>>> listB
[2, 3]
However, it's often much cleaner to go the functional way and not modify the original list at all, instead just creating a new list with the values you need. You can use list comprehensions to do that elegantly:
>>> lst = [1,2,3]
>>> small = [a for a in lst if a < 2]
>>> big = [a for a in lst if a >= 2]
>>> small
[1]
>>> big
[2, 3]
Upvotes: 16