'How do I move items from one list to another? [duplicate]

I am trying to remove all the items from list2 into list1 like this:

l1 = [1, 2, 3]
l2 = [4, 5, 6]

for item in l2:
    l1.append(item)
    l2.remove(item)

the problem is:

#l1 now returns [1, 2, 3, 4, 6]
#l2 now returns [5]

I want it so that:

#l1 returns [1, 2, 3, 4, 5, 6]
#l2 returns []

Why does this happen? And what is the conventional way to achieve what I'm trying to do, in Python?



Solution 1:[1]

Your code doesn't work because you are removing items while iterating.

For your problem - moving all items from one list to another list - the best solution is to use built-in methods provided by lists (the latter since Python 3.3):

l1.extend(l2)
l2.clear()

you can replace l2.clear() with l2 = [] if there are no other references to l2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMD