rectangletangle rectangletangle - 4 months ago 9
Python Question

How do I remove the first Item from a Python list?


Possible Duplicate:

good primer for python slice notation




I have the list
[0, 1, 2, 3, 4]
I'd like to make it into
[1, 2, 3, 4]
. How do I go about this?

Answer

Python List

list.pop(index)

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

del list[index]

>>> l = [0, 1, 2, 3, 4]
>>> del l[0]
>>> l
[1, 2, 3, 4]

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([0, 1, 2, 3, 4])
>>> l.popleft()
0
>>> l
deque([1, 2, 3, 4])
  • Provides higher perfomance popping from left end of the list