Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

performance - What is the fastest way to merge two lists in python?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...