Optimal solution to extend a python list by adding the at the beginning of the list instead of tail?

>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> x = y+x

This simple solution runs twice as fast as the solution with deque for smaller input sizes:

$ cat x1.py 
for i in range(1000000):
    x = ['a', 'b', 'c']
    y = [1, 2, 3]
    x = y+x

$ cat x2.py 
from collections import deque
for i in range(1000000):
    d = deque(['a', 'b', 'c'])
    d.extendleft(reversed([1, 2, 3]))

$ time python x1.py

real    0m1.912s
user    0m1.864s
sys     0m0.040s

$ time python x2.py

real    0m5.368s
user    0m5.316s
sys     0m0.052s

However, it becomes slower for larger sizes of input:

>python -m timeit -s "y = range(100000)" "x = list(xrange(10000000)); y+x"
10 loops, best of 3: 229 msec per loop

>python -m timeit -s "from collections import deque; y = range(100000)" "d = deque(xrange(10000000)); d.extendleft(reversed(y))"
10 loops, best of 3: 178 msec per loop

When you want to append on the left, a deque is much more efficient than a list. Use the extendleft method.

>>> from collections import deque
>>> d = deque(['a', 'b', 'c'])
>>> d.extendleft(reversed([1, 2, 3]))
>>> d
deque([1, 2, 3, 'a', 'b', 'c'])

If you always append on the left only, consider keeping the elements in a list in reverse order.


x[0:0] = y
  • notationally simple
  • performance characteristics: unknown
  • preserves id(x)