Sometimes we require to merge two lists that are sorted. This type of sorting is known as merge sorting. There are various ways to merge two sorted lists in python. In this entire tutorial, you will know how to merge two sorted lists in python with various examples.
Methods to Merge two sorted lists in Python
In this section, you will know all the methods you can use to merge two already sorted lists in python. Let’s know each of them.
Method 1: Using the sorted() function
You can use the python inbuilt function sorted() for sorting the two combined lists. Here you have to first append the list and then pass the combined list as an argument of the sorted() function. Execute the below lines of code and see the output.
list1 = [1,2,3,4,5]
list2= [10,20,30,40,50,60]
print(sorted(list1 + list2))
Output
Method 2: Using the heapq merge
The second method to combine two already sorted lists is using the heapq module. It has a merge method that meger the lists in a sorted way. Just execute the below lines of code.
from heapq import merge
list1 = [1,2,3,4,5]
list2= [10,20,30,40,50,60]
print(list(merge(list1,list2)))
Output
Method 3: Merge two sorted lists using stack
You can merge two sorted lists using a stack. In this method, you have to treat each sorted list as a stack. After that, continuously pop the smaller elements from the top of the stack and append the popped item to the list. It will continue to do so until the stack is empty. At last, the remaining elements of the list will be appended to the final list.
Execute the below lines of code and see the output.
list1 = [1,2,3,4,5]
list2= [10,20,30,40,50,60]
#Using stack
sorted_list =[]
while list1 and list2:
if list1[0] < list2[0]:
sorted_list.append(list1.pop(0))
else:
sorted_list.append(list2.pop(0))
sorted_list += list1
sorted_list += list2
print(sorted_list)
Output
These are the methods to merge two sorted lists. You can use any one of them. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.