How to Interleave Two Lists in Python Until One List Exhausted
Interleave elements from two lists pairwise using zip, stopping when either list runs out of items.
Python code
10 linesdef interleave(a, b):
result = []
for x, y in zip(a, b):
result.extend([x, y])
return result
if __name__ == "__main__":
list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c"]
print(interleave(list1, list2))
Output
[1, 'a', 2, 'b', 3, 'c']
How it works
The zip function pairs elements from both lists at the same index, creating tuples like (1, 'a'). The loop unpacks each tuple into x and y, then extend appends both in order, preserving the interleaving. Because zip stops at the end of the shorter list, the result contains only the fully paired elements, which matches the requirement to stop when one list is exhausted. This approach is concise and efficient, as it avoids manual index tracking.
Common mistakes
- Using `zip_longest` from itertools, which continues past the shorter list and fills missing values with a default.
- Forgetting that `zip` yields tuples; you must unpack them or use `itertools.chain` to flatten.
Variations
- Use `itertools.chain.from_iterable(zip(a, b))` to produce an iterator instead of a list.
- Use a list comprehension: `[item for pair in zip(a, b) for item in pair]`.
Real-world use cases
- Combining two time-series sensors' readings into a single synchronized row for logging.
- Merging alternating values from two configuration arrays into a single settings list.
- Building a pattern for a UI layout where items from two categories alternate in a fixed order.
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.