How to remove the first Item from a list? How to remove the first Item from a list? python python

How to remove the first Item from a list?


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:

  • Copies the list
  • Can return a subset

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'>>> ldeque(['b', 'c', 'd'])
  • Provides higher performance popping from left end of the list


Slicing:

x = [0,1,2,3,4]x = x[1:]

Which would actually return a subset of the original but not modify it.


>>> x = [0, 1, 2, 3, 4]>>> x.pop(0)0

More on this here.


matomo