Round Robin Merge Multiple Lists in Python

Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.

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

Python code

20 lines
Python 3.9+
from itertools import cycle

def round_robin_merge(*lists):
    """Merge multiple lists by taking one element from each in turn."""
    result = []
    max_len = max(len(lst) for lst in lists)
    
    for i in range(max_len):
        for lst in lists:
            if i < len(lst):
                result.append(lst[i])
    return result

if __name__ == "__main__":
    list1 = [1, 2, 3]
    list2 = ['a', 'b']
    list3 = [10, 20, 30, 40]
    
    merged = round_robin_merge(list1, list2, list3)
    print(merged)

Output

stdout
[1, 'a', 10, 2, 'b', 20, 3, 30, 40]

How it works

The function uses a loop over the maximum list length to control how many rounds of merging occur. An inner loop iterates over each input list, appending the element at the current index only if that index exists in the list — this naturally handles lists of different lengths. The result preserves the order of input lists and interleaves elements round by round. This approach is clear and readable, making it easy to modify for custom orders or filtering conditions.

Common mistakes

  • Using zip() which stops at the shortest list, dropping extra elements
  • Appending None or a placeholder when lists run out instead of skipping
  • Forgetting to handle empty input lists, which causes max() to raise ValueError
  • Mutating the original lists while merging

Variations

  1. Use itertools.zip_longest with a fill value and filter it out for a one-liner approach
  2. Use a queue-based approach with collections.deque for efficient rotation patterns

Real-world use cases

  • Interleaving results from multiple paginated API responses into a unified feed for display.
  • Merging logs from several microservices into a single chronological timeline for debugging.
  • Combining items from multiple queues into a single ordered stream for a job scheduler.

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.