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.
Python next() method Syntax Return : Returns next element from the list, if not present prints the default value. If default value is not present, raises the StopIteration error.
To move an element to the end of a list: Use the list. append() method to append the value to the end of the list. Use the del statement to delete the original element from the list.
To find the index of an element in a list, you use the index() function. It returns 3 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
:
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With