Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

You have

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

And want to insert list y at the beginning of x:

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

What is the optimal solution to do this in Python?

like image 653
sorin Avatar asked Jun 19 '12 10:06

sorin


People also ask

How do you extend the length of a list in Python?

The list extend() method in Python is used to add the elements of the iterable at the end of the current list as list elements. The length of the iterable increases the length of the original list. On the other hand, the list append() method is used to add the object at the end of the current list as a single element.

How append () and extend () are different with reference to list in Python?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

How do you extend one list to another in Python?

append() adds the new elements as another list, by appending the object to the end. To actually concatenate (add) lists together, and combine all items from one list to another, you need to use the . extend() method.

Which method is best to use when adding an item to the end of a list?

If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert .


1 Answers

>>> 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
like image 55
Ashwini Chaudhary Avatar answered Oct 05 '22 18:10

Ashwini Chaudhary