Given,
list_1 = [1,2,3,4]
list_2 = [5,6,7,8]
What is the fastest way to achieve the following in python?
l
If you are using python 3, there is one more way to do this and a little bit faster (tested only on python 3.7)
[*list1, *list2]
Benchmark
from timeit import timeit
x = list(range(10000))
y = list(x)
def one():
x + y
def two():
[*x, *y]
print(timeit(one, number=1000, globals={'x':x, 'y': y}))
print(timeit(two, number=1000, globals={'x':x, 'y': y}))
0.10456193100253586
0.09631731400440913
I tested out several ways to merge two lists (see below) and came up with the following order after running each several times to normalize the cache changes (which make about a 15% difference).
import time
c = list(range(1,10000000))
c_n = list(range(10000000, 20000000))
start = time.time()
*insert method here*
print (time.time()-start)
Method 1: c.extend(c_n)
Method 2: c += c_n
Method 3: c = c + c_n
Method 4: c = [*c, *c_n]
Conclusion
Use +=
or .extend()
if you want to merge in place. They are significantly faster.
list_1 + list_2
does it. Example -
>>> list_1 = [1,2,3,4]
>>> list_2 = [5,6,7,8]
>>> list_1 + list_2
[1, 2, 3, 4, 5, 6, 7, 8]
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)
OUTPUT:
>>> [1, 2, 3, 4, 5, 6]
In the above code "+" operator is used to concatenate the 2 lists into a single list.
ANOTHER SOLUTION:
a=[1,2,3]
b=[4,5,6]
c=[] #Empty list in which we are going to append the values of list (a) and (b)
for i in a:
c.append(i)
for j in b:
c.append(j)
print(c)
OUTPUT:
>>> [1, 2, 3, 4, 5, 6]
You can just use concatenation:
list = list_1 + list_2
If you don't need to keep list_1 around, you can just modify it:
list_1.extend(list_2)