Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Using + Operator with 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 ?
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 :", res)
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']
Using heapq.merge()
The merge function from heapq module can combine the elements of two sorted lists efficiently. It returns an iterator that merges the lists in sorted order ?
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 and convert to list
res = list(merge(sorted(listA), sorted(listB)))
# Result
print("The combined sorted list is :", res)
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']
Using extend() Method
The extend() method adds all elements from one list to another, then we can sort the result ?
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu', 'Fri', 'Sat']
# Given lists
print("Given list A is :", listA)
print("Given list B is :", listB)
# Extend and sort
combined = listA.copy() # Create a copy to avoid modifying original
combined.extend(listB)
res = sorted(combined)
# Result
print("The combined sorted list is :", res)
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']
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
sorted(listA + listB) |
O(n log n) | Simple combination and sorting |
heapq.merge() |
O(n) | Already sorted lists |
extend() + sorted() |
O(n log n) | In-place operations |
Conclusion
Use sorted(listA + listB) for simple list combination. Use heapq.merge() when working with already sorted lists for better performance. Use extend() when you need to modify an existing list.
