0

Can anyone explain the logic behind this code?

def move(list1,list2):
    for num in list1: 
        list2.append(num)
        list1.remove(num)
list1=[1,2,3,4,5]
list2=[10]
move(list1,list2)
print(list1,list2)

I have been trying to figure out why the output is

[2, 4] [10, 1, 3, 5]

but not

[] [10,1,2,3,4,5]

Shouldn't all the num in list1 move to list2? I'm still a beginner in python.

  • you modify the list you iterate on – bruno Apr 15 '20 at 12:54
  • This is exactly because you are removing items from list while iterating over. Don't cut off the branch where you sit, it can cause unexpected results. – Austin Apr 15 '20 at 12:54

3 Answers3

1

You should not remove from a list that you are iterating. As you can see, you will be skipping elements. You can do this more easily, using list.extend and list.clear:

def move(list1, list2):
    list2.extend(list1)
    list1.clear()

And if you like a one-liner, you can go for:

def move(list1, list2):
    list1[:], list2[:] = [], list2+list1
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

While your for loop goes forward -> you initial list shrinks.

index of used element 1
-----------
initial list [1, 2, 3, 4, 5]
item added to list2 1
item removed from list1 1
----------------------------
index of used element 2
-----------
initial list [2, 3, 4, 5]
item added to list2 3
item removed from list1 3
----------------------------
index of used element 3
-----------
initial list [2, 4, 5]
item added to list2 5
item removed from list1 5
----------------------------
[2, 4] [10, 1, 3, 5]

As you can see on the third iteration, the for loop reaches the last element of the initial list, which is 5.

2 and 4 are skipped because the list got shrunk E.g. initial_list[2] becomes 3 instead of 2 because the initial list become[2,3..] after the removal of 1.

andreis11
  • 1,133
  • 1
  • 6
  • 10
-1

I think you should use extend method. Here is how to use it:

list2.extend(list1)
list1 = []
Ambitions
  • 2,369
  • 3
  • 13
  • 24
  • Note that this is in a function. `list1 = []` will only rebind the local variable, but not mutate the list object passed in as an argument. You would have to do `list1[:] = []` or `list1.clear()` to do that. – user2390182 Apr 15 '20 at 13:08