Combining two sorted lists in Python


Lists are one of the most extensively used python data structures. In this article we will see how to combine the elements of two lists and produce the final output in a sorted manner.

With + and sorted

The + operator can join the elements of two lists into one. Then we apply the sorted function which will sort the elements of the final list created with this combination.

Example

 Live Demo

listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Add and sort
res = sorted(listA + listB)
# Result
print("The combined sorted list is : \n" ,res)

Output

Running the above code gives us the following result −

Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']

With merge

The merge function from heapq module can combine the elements of two lists. Then we apply the sorted function to get the final output.

Example

 Live Demo

from heapq import merge
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Merge
res = list(merge(listA,listB))
# Result
print("The combined sorted list is : \n" ,sorted(res))

Output

Running the above code gives us the following result −

Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']

Updated on: 20-May-2020

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements