How to remove the first Item from a list?
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?
>>> l = ['a', 'b', 'c', 'd'] >>> l.pop(0) 'a' >>> l ['b', 'c', 'd'] >>>
>>> l = ['a', 'b', 'c', 'd'] >>> del l >>> 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' >>> l deque(['b', 'c', 'd'])
- Provides higher performance popping from left end of the list
Read more... Read less...
x = [0,1,2,3,4] x = x[1:]
Which would actually return a subset of the original but not modify it.
you would just do this
l = [0, 1, 2, 3, 4] l.pop(0)
l = l[1:]
Pros and Cons
Using pop you can retrieve the value
x = l.pop(0)
x would be
Then just delete it:
x = [0, 1, 2, 3, 4] del x print x # [1, 2, 3, 4]