Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Naffi Avatar asked Jun 11 '13 12:06

Naffi


People also ask

How do I merge two lists in Python?

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items, instead, it modifies the original list by adding the item to the end of the list.

How do I put multiple lists into one list?

Here, a for loop is used for adding the two lists using the append() method. This process is used as the append() method adds a single element to the end of a list. Thus, each element of the list2 is added to list1, one by one using the for loop.


1 Answers

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) 
like image 148
phant0m Avatar answered Sep 28 '22 06:09

phant0m