Search code examples
pythonperformancelistpython-2.7python-3.x

The most efficient way to remove first N elements in a list?


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


Solution

  • You can use list slicing to archive 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]