Creating a Sorted Merged List of Two Unsorted Lists in Python
Last Updated :
17 Jan, 2025
Improve
Creating a sorted merged list of two unsorted lists involves combining the elements of both lists and sorting the resulting list in ascending order.
For example: If we have list1 = [25, 18, 9]
and list2 = [45, 3, 32]
the output will be [3, 9, 18, 25, 32, 45].
Using +
Operator
This method merges the two lists using the +
operator which concatenates them and then combined list is sorted using the sort()
method.
a = [25, 18, 9, 41, 26, 31]
b = [25, 45, 3, 32, 15, 20]
# Merge and sort using + operator and sort()
res = a + b
res.sort()
print(res)
a = [25, 18, 9, 41, 26, 31]
b = [25, 45, 3, 32, 15, 20]
# Merge and sort using + operator and sort()
res = a + b
res.sort()
print(res)
Output
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]
Explanation:
+
operator concatenatesl1
andl2
into a single list.sort()
function rearranges the elements of the combined list in ascending order.
Using heapq.merge()
This method uses the merge()
function from Python's heapq
module which merges two sorted iterables into a single sorted iterable. The lists are first individually sorted then merged using heapq.merge()
.
import heapq
a = [25, 18, 9, 41, 26, 31]
b = [25, 45, 3, 32, 15, 20]
# Merge and sort using heapq.merge()
a.sort()
b.sort()
res = list(heapq.merge(a,b))
print(res)
import heapq
a = [25, 18, 9, 41, 26, 31]
b = [25, 45, 3, 32, 15, 20]
# Merge and sort using heapq.merge()
a.sort()
b.sort()
res = list(heapq.merge(a,b))
print(res)
Output
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]
Explanation:
- Input lists (
a
andb
) are sorted individually usingsort()
. heapq.merge()
function combines the two sorted lists into a single sorted iterable which is converted to a list usinglist()
.