Python program to merge two lists and sort the merged list
Python program to merge two lists and sort it
In this post, you will learn the Python program to merge two lists and sort them.
A list is a sequence of indexed and ordered values. It is mutable, which means we can change the order of elements in a list. It contains a list of any type of data objects with a comma separated and enclosed within a square bracket. Each element of the list has an index, starting with 0, 1 and so on. For accessing an item, a square bracket is used with the list name.
When we are working with multiple lists, we may come to the situation where we need to merge two lists and sort them. In this post, we will use integer numbers in both lists so that we can easily sort them.
Python Program to Merge Two Lists
This article is created to cover some programs in Python that merges two lists in different-different ways. Here are the list of programs on merging of two lists, available in this article:
- Merge two lists of 6-6 elements
- Merge two lists of given size of elements
- Merge two lists in ascending order
- Merge two lists in descending order
Python | Combining two sorted lists
Many a times we encounter a problem where we wish to use the merge function of merge sort and is a classical problem that occurs many times while doing competitive programming. This type of problem when known shorter and compact way to perform them are always quite handy.
Let’s discuss certain ways of combining two sorted list in Python.
Method #1 : Naive Method
Merge operation of merge sort can be performed using the naive method which has also been discussed earlier. We check for the smaller of two element on the current index and increment the index of the list whose no. is encountered. When either of the list gets exhausted, the other list is appended to the end of merged list.
# Python3 code to demonstrate
# to combine two sorted list
# using naive method
# initializing lists
test_list1 = [1, 5, 6, 9, 11]
test_list2 = [3, 4, 7, 8, 10]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using naive method
# to combine two sorted lists
size_1 = len(test_list1)
size_2 = len(test_list2)
res = []
i, j = 0, 0
while i < size_1 and j < size_2:
if test_list1[i] < test_list2[j]:
res.append(test_list1[i])
i += 1
else:
res.append(test_list2[j])
j += 1
res = res + test_list1[i:] + test_list2[j:]
# printing result
print ("The combined sorted list is : " + str(res))
|
The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Method #2 : Using sorted()
This function can be used to perform this task in just a 1 line but will take more time internally. It may have more time complexity as we append one list to another and again sort the resultant list. Should be used if we need to save the coding time.
# Python3 code to demonstrate
# to combine two sorted list
# using sorted()
# initializing lists
test_list1 = [1, 5, 6, 9, 11]
test_list2 = [3, 4, 7, 8, 10]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using sorted()
# to combine two sorted lists
res = sorted(test_list1 + test_list2)
# printing result
print ("The combined sorted list is : " + str(res))
|
Method #3 : Using heapq.merge()
Python also offers the inbuilt function to perform this particular task and performs the similar working in background as merge in naive method and should be used when wanting to deal with this kind of problem.
# Python3 code to demonstrate
# to combine two sorted list
# using heapq.merge()
from heapq import merge
# initializing lists
test_list1 = [1, 5, 6, 9, 11]
test_list2 = [3, 4, 7, 8, 10]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using heapq.merge()
# to combine two sorted lists
res = list(merge(test_list1, test_list2))
# printing result
print ("The combined sorted list is : " + str(res))
|
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Ways to concatenate two lists in Python
Let’s see how to concatenate two lists using different methods in Python. This operation is useful when we have numbers of lists of elements which needs to be processed in a similar manner.
Method #1 : Using Naive Method
In this method, we traverse the second list and keep appending elements in the first list, so that first list would have all the elements in both lists and hence would perform the append.
# Python3 code to demonstrate list
# concatenation using naive method
# Initializing lists
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
# using naive method to concat
for i in test_list2 :
test_list1.append(i)
# Printing concatenated list
print ("Concatenated list using naive method : "
+ str(test_list1))
|
Method #2 : Using + operator
The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation.
# Python 3 code to demonstrate list
# concatenation using + operator
# Initializing lists
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
# using + operator to concat
test_list3 = test_list3 + test_list4
# Printing concatenated list
print ("Concatenated list using + : "
+ str(test_list3))
|
Method #3 : Using list comprehension
List comprehension can also accomplish this task of list concatenation. In this case, a new list is created, but this method is a one liner alternative to the loop method discussed above.
# Python3 code to demonstrate list
# concatenation using list comprehension
# Initializing lists
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
# using list comprehension to concat
res_list = [y for x in [test_list1, test_list2] for y in x]
# Printing concatenated list
print ("Concatenated list using list comprehension: "
+ str(res_list))
|
Method #4 : Using extend()
extend() is the function extended by lists in Python and hence can be used to perform this task. This function performs the inplace extension of first list.
# Python3 code to demonstrate list
# concatenation using list.extend()
# Initializing lists
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
# using list.extend() to concat
test_list3.extend(test_list4)
# Printing concatenated list
print ("Concatenated list using list.extend() : "
+ str(test_list3))
|
Method #5 : Using * operator
Using * operator, this method is the new addition to list concatenation and works only in Python 3.6+. Any no. of lists can be concatenated and returned in a new list using this operator.
# Python3 code to demonstrate list
# concatenation using * operator
# Initializing lists
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
# using * operator to concat
res_list = [*test_list1, *test_list2]
# Printing concatenated list
print ("Concatenated list using * operator : "
+ str(res_list))
|
Method #6 : Using itertools.chain()
itertools.chain() returns the iterable after chaining its arguments in one and hence does not require to store the concatenated list if only its initial iteration is required. This is useful when concatenated list has to be used just once.
# Python3 code to demonstrate list
# concatenation using itertools.chain()
import itertools
# Initializing lists
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
# using itertools.chain() to concat
res_list = list(itertools.chain(test_list1, test_list2))
# Printing concatenated list
print ("Concatenated list using itertools.chain() : "
+ str(res_list))
|
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python program to merge two lists and sort it
In this tutorial, we will learn about writing a Python program to merge two lists and then sort it
This tutorial may also be helpful while working on multiple lists.
Python allows merging just by using ‘ + ‘ operator as any number of lists can be merged using this operator. For instance, let us see an example
Merging Lists in Python
Let’s learn about different ways to merge the lists in python.
Merging List in Python
List:
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might…