Round Robin Merge Multiple Lists in Python
Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.
Python code
20 linesfrom 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
[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
- Use itertools.zip_longest with a fill value and filter it out for a one-liner approach
- 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
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.