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?
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.
append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.
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.
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 .
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With