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

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    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))

    Continue reading...

Compartilhe esta Página