Merge Two Sorted Lists in Python Know various methods

Merge Two Sorted Lists in Python: Know various methods

Popular Domains for just 99 Cents at Namecheap!

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 inbuild function sorted() for sorting the two combine 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

Merging two sorted list
Merging two sorted list

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

Merging two sorted list using heapq
Merging two sorted lists using heapq

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

Merging two sorted list using stack
Merging two sorted lists using stack

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.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner