pythonlist

How do I remove the first item from a list?


How do I remove the first item from a list?

[0, 1, 2, 3]   →   [1, 2, 3]

Solution

  • You can find a short collection of useful list functions here.

    list.pop(index)

    >>> l = ['a', 'b', 'c', 'd']
    >>> l.pop(0)
    'a'
    >>> l
    ['b', 'c', 'd']
    >>> 
    

    del list[index]

    >>> l = ['a', 'b', 'c', 'd']
    >>> del l[0]
    >>> l
    ['b', 'c', 'd']
    >>> 
    

    These both modify your original list.

    Others have suggested using slicing:

    Also, if you are performing many pop(0), you should look at collections.deque

    from collections import deque
    >>> l = deque(['a', 'b', 'c', 'd'])
    >>> l.popleft()
    'a'
    >>> l
    deque(['b', 'c', 'd'])