Question about `list.insert`

Peter Otten __peter__ at web.de
Fri Feb 7 03:25:10 EST 2014


cool-RR wrote:

> I'm curious. If I append an item to a list from the left using
> `list.insert`, will Python always move the entire list one item to the
> right (which can be super-slow) or will it check first to see whether it
> can just allocate more memory to the left of the list and put the item
> there, saving a lot of resources?

Let's see:

$ python3.4 -m timeit -s 'a = [None]' 'a.insert(0, None); del a[0]'
1000000 loops, best of 3: 0.596 usec per loop
$ python3.4 -m timeit -s 'a = [None]*1000' 'a.insert(0, None); del a[0]'
100000 loops, best of 3: 2.59 usec per loop
$ python3.4 -m timeit -s 'a = [None]*10000' 'a.insert(0, None); del a[0]'
10000 loops, best of 3: 24.7 usec per loop
$ python3.4 -m timeit -s 'a = [None]*100000' 'a.insert(0, None); del a[0]'
1000 loops, best of 3: 508 usec per loop
$ python3.4 -m timeit -s 'a = [None]*1000000' 'a.insert(0, None); del a[0]'
100 loops, best of 3: 7.61 msec per loop

$ python3.4 -m timeit -s 'from collections import deque; a = 
deque([None]*1000000)' 'a.appendleft(None); a.popleft()'
1000000 loops, best of 3: 0.263 usec per loop





More information about the Python-list mailing list