Given,
list_1 = [1,2,3,4]
list_2 = [5,6,7,8]
What is the fastest way to achieve the following in python?
list = [1,2,3,4,5,6,7,8]
Please note that there can be many ways to merge two lists in python.
I am looking for the most time-efficient way.
I tried the following and here is my understanding.
CODE
import time
c = list(range(1,10000000))
c_n = list(range(10000000, 20000000))
start = time.time()
c = c+c_n
print len(c)
print time.time() - start
c = list(range(1,10000000))
start = time.time()
for i in c_n:
c.append(i)
print len(c)
print time.time() - start
c = list(range(1,10000000))
start = time.time()
c.extend(c_n)
print len(c)
print time.time() - start
OUTPUT
19999999
0.125061035156
19999999
1.02858018875
19999999
0.03928399086
So, if someone does not bother reusing list_1/list_2 in the question then extend is the way to go. On the other hand, "+" is the fastest way.
I am not sure about other options though.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…