How to Merge Two Sorted Lists in Python
Merge two sorted lists into one sorted list using a two-pointer loop, then extend with remaining elements.
Python code
22 linesdef merge_sorted_lists(list1, list2):
merged = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
merged.extend(list1[i:])
merged.extend(list2[j:])
return merged
if __name__ == "__main__":
a = [1, 3, 5, 7]
b = [2, 4, 6, 8, 10]
result = merge_sorted_lists(a, b)
print(f"Merged: {result}")
Output
Merged: [1, 2, 3, 4, 5, 6, 7, 8, 10]
How it works
The two-pointer technique walks through both lists in parallel, always appending the smaller of the two current values. This gives O(n+m) time complexity since each list is only traversed once. After one list is exhausted, the remaining elements of the other list are already sorted, so extend appends them directly. This is exactly the merge step used in merge sort.
Common mistakes
- Forgetting to handle leftover elements after the main loop with extend.
- Using index-based lookups that fail when arrays of different lengths.
- Modifying input lists in place instead of returning a new merged list.
Variations
- Use `heapq.merge(list1, list2)` from the stdlib for a lazy iterator of the merged result.
- Apply `sorted(list1 + list2)` for simplicity, though it's O((n+m) log(n+m)) instead of linear.
Real-world use cases
- Merging sorted pagination results from multiple API endpoints into one unified feed.
- Combining timestamp-sorted log files during batch processing in a data pipeline.
- Joining two sorted index files when compacting a database's inverted index.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.