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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
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

  1. Use `heapq.merge(list1, list2)` from the stdlib for a lazy iterator of the merged result.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.