Skip to content Skip to sidebar Skip to footer

Moving Python Elements Between Lists

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

Solution 1:

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]

Post a Comment for "Moving Python Elements Between Lists"