Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Python Elements between Lists

Tags:

python

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.

like image 457
devinpleuler Avatar asked Apr 02 '12 02:04

devinpleuler


People also ask

How do you get the next element while cycling through a list in Python?

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.

How do you move an element to the end of a list in Python?

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.

How do you find the index of a value in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected.


1 Answers

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]
like image 114
Niklas B. Avatar answered Sep 27 '22 22:09

Niklas B.