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.
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:Example:
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: