Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.
Lists are not optimized for modifications at the front, and somelist.insert(0, something)
is an O(n) operation.
somelist.pop(0)
and del somelist[0]
are also O(n) operations.
The correct data structure to use is a deque from the collections
module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have an appendleft
method for insertions at the front.
Demo:
In [1]: lst = [0]*1000
In [2]: timeit -n1000 lst.insert(0, 1)
1000 loops, best of 3: 794 ns per loop
In [3]: from collections import deque
In [4]: deq = deque([0]*1000)
In [5]: timeit -n1000 deq.appendleft(1)
1000 loops, best of 3: 73 ns per loop