Open In App

Creating a Sorted Merged List of Two Unsorted Lists in Python

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
4 Likes
Like
Report

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.


Output
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]

Explanation:

  • + operator concatenates l1 and l2 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().


Output
[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]

Explanation:

  • Input lists (a and b) are sorted individually using sort().
  • heapq.merge() function combines the two sorted lists into a single sorted iterable which is converted to a list using list().

Next Article
Practice Tags :

Similar Reads