python

In Python how do you pop the first n elements of a list and append these to a new list?


How do I pop the first n elements of a list and append these to a different list?

so, for example.

mylist = []
n = 3
mainlist = [5,4,3,2,1]

How would I make it so I have

mainlist = [2,1]

mylist = [5,4,3]

I've tried the following but it doesn't work as the placement of the elements are changing after each loop:

for i in list(range(n)):
    mylist.append(mainlist.pop(i))

Solution

  • You could just slice the list:

    mainlist = [5,4,3,2,1]
    n = 3
    mainlist, mylist = mainlist[:n], mainlist[n:]
    

    Keep in mind that for slicing, the first index is inclusive, while the second is exclusive, so mainlist wouldn't contain index 3 but mylist would.