snippetpythonCritical
How do I remove the first item from a list?
Viewed 0 times
howlisttheitemremovefirstfrom
Problem
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.
These both modify your original list.
Others have suggested using slicing:
Also, if you are performing many
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.dequefrom collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])- Provides higher performance popping from left end of the list
Code Snippets
>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']
>>>>>> l = ['a', 'b', 'c', 'd']
>>> del l[0]
>>> l
['b', 'c', 'd']
>>>from collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])Context
Stack Overflow Q#4426663, score: 1697
Revisions (0)
No revisions yet.