-1

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?

tonitone120
  • 1,920
  • 3
  • 8
  • 25

1 Answers1

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

Luatic
  • 8,513
  • 2
  • 13
  • 34