0
0
PythonHow-ToBeginner · 3 min read

How to Use itertools.chain in Python: Syntax and Examples

Use itertools.chain to combine multiple iterables into a single iterable that yields elements from each input one after another. Import it with from itertools import chain and pass your iterables as arguments to chain().
📐

Syntax

The itertools.chain function takes multiple iterable objects as arguments and returns a single iterable that produces elements from the first iterable until it is exhausted, then continues to the next iterable, and so on.

  • chain(iter1, iter2, ...): Combines multiple iterables.
  • chain.from_iterable(iterable_of_iterables): Takes a single iterable containing iterables and chains them.
python
from itertools import chain

# Basic syntax
combined = chain([1, 2], ['a', 'b'])

# Using from_iterable
combined_from_iterables = chain.from_iterable([[1, 2], ['a', 'b']])
💻

Example

This example shows how to use chain to combine two lists and iterate over all their elements as if they were one sequence.

python
from itertools import chain

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

for item in chain(list1, list2):
    print(item)
Output
1 2 3 a b c
⚠️

Common Pitfalls

One common mistake is trying to concatenate iterables using + which only works for sequences like lists, not all iterables. Another is forgetting to import chain from itertools. Also, using chain with non-iterables will cause errors.

Use chain.from_iterable when you have a single iterable containing multiple iterables, instead of passing them as separate arguments.

python
from itertools import chain

# Wrong: trying to add generators (will raise TypeError)
g1 = (x for x in range(3))
g2 = (x for x in range(3,6))

# combined = g1 + g2  # This is invalid

# Right: use chain to combine generators
combined = chain(g1, g2)
print(list(combined))
Output
[0, 1, 2, 3, 4, 5]
📊

Quick Reference

FunctionDescription
chain(iter1, iter2, ...)Combine multiple iterables into one sequence
chain.from_iterable(iterable_of_iterables)Combine iterables contained in a single iterable
ReturnsAn iterator that yields elements from each iterable in order

Key Takeaways

Use itertools.chain to combine multiple iterables into a single iterable without creating intermediate lists.
Import chain with 'from itertools import chain' before using it.
Use chain.from_iterable when chaining a single iterable containing multiple iterables.
chain works with any iterable, including lists, tuples, generators, and more.
Avoid using '+' to combine non-sequence iterables; chain is the correct tool.