0
0
PythonHow-ToBeginner · 3 min read

How to Interleave Two Lists in Python: Simple Guide

To interleave two lists in Python, use zip() to pair elements and a list comprehension to flatten them. This combines elements alternately from both lists into a single list.
📐

Syntax

The basic syntax to interleave two lists list1 and list2 is:

  • zip(list1, list2) pairs elements from both lists.
  • A list comprehension [item for pair in zip(list1, list2) for item in pair] flattens these pairs into one list.
python
interleaved = [item for pair in zip(list1, list2) for item in pair]
💻

Example

This example shows how to interleave two lists of equal length:

python
list1 = [1, 3, 5]
list2 = [2, 4, 6]
interleaved = [item for pair in zip(list1, list2) for item in pair]
print(interleaved)
Output
[1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

One common mistake is assuming zip() works with lists of different lengths without losing elements. zip() stops at the shortest list, so extra elements in the longer list are ignored.

To handle lists of different lengths, use itertools.zip_longest() with a fill value.

python
from itertools import zip_longest

list1 = [1, 3, 5, 7]
list2 = [2, 4]

# Using zip (loses extra elements)
interleaved_zip = [item for pair in zip(list1, list2) for item in pair]
print(interleaved_zip)  # Output: [1, 2, 3, 4]

# Using zip_longest (keeps all elements, fills missing with None)
interleaved_longest = [item for pair in zip_longest(list1, list2) for item in pair if item is not None]
print(interleaved_longest)  # Output: [1, 2, 3, 4, 5, 7]
Output
[1, 2, 3, 4] [1, 2, 3, 4, 5, 7]
📊

Quick Reference

Tips for interleaving lists in Python:

  • Use zip() for equal-length lists.
  • Use itertools.zip_longest() to handle different lengths.
  • Flatten pairs with a list comprehension.
  • Remember zip() stops at the shortest list.

Key Takeaways

Use zip() and a list comprehension to interleave two lists cleanly.
zip() stops at the shortest list, so extra elements are lost if lists differ in length.
Use itertools.zip_longest() to include all elements when lists have different lengths.
Flatten pairs from zip() with a nested list comprehension for the final interleaved list.