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.

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

Python code

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

stdout
[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

  1. Use `itertools.chain.from_iterable(zip(a, b))` to produce an iterator instead of a list.
  2. 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

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.