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.
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.
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.
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)
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