pythonlistperformance

The most efficient way to remove the first N elements from a list


I need to remove the first N elements from a list of objects. Is there an easy way, without using loops?


Solution

  • You can use list slicing to achieve your goal.

    Remove the first 5 elements:

    n = 5
    mylist = [1,2,3,4,5,6,7,8,9]
    newlist = mylist[n:]
    print(newlist)
    

    Outputs:

    [6, 7, 8, 9]
    

    Or del if you only want to use one list:

    n = 5
    mylist = [1,2,3,4,5,6,7,8,9]
    del mylist[:n]
    print(mylist)
    

    Outputs:

    [6, 7, 8, 9]