Home > Software design >  How to remove 1 element from 1 list and add to it into another one. Repeat this for the entire list
How to remove 1 element from 1 list and add to it into another one. Repeat this for the entire list

Time:03-03

I have a List of element:

L = [1,2,3]

I would like to pop element from list L and add them to another list L2:

I am trying the following code:

for i in range(len(L)):
    L2.append(L.pop())

But is not working

CodePudding user response:

What do you mean not working, I put in your code to debug it and see what error it gives. But your code works fine.

L = [1,2,3]
L1 = []

print(L)
for i in range(len(L)):
    L1.append(L.pop())
print(L1)

Output

[1, 2, 3]
[3, 2, 1]

Also of course by popping elements you get a reverse list, if you want the exact same list, you just do L1 = L or in the for loop just go L1.append(L[i])

  • Related