chain
- Python course
- Intermediate
- Lesson 94/116
- 5 min
Learn chaining with itertools.chain.
chain
chain is a function from the itertools module that combines several iterables into a single iterable. It gives sequential access without creating a nested list.
Example: list(chain([1, 2], [3, 4])) returns [1, 2, 3, 4]. chain walks all items one by one; it does not produce a new list, it returns an iterator. This is good for memory; merging large data does not create a copy.
Returns an iterator
chain does not return a list directly; it returns an iterator. To see the result you use list() or a for loop. This is memory efficient; all items are not loaded at once.
To flatten nested lists you can use chain.from_iterable([[1, 2], [3, 4]]). This gives the same result as chain(*[[1, 2], [3, 4]]) but works with a single argument. It is ideal for dynamically generated iterables.
Practice Merge lists with chain
Start with from itertools import chain. Merge two lists with result = list(chain([1, 2], [3, 4])). Then print the result with print(result).
Starter code
# Merge two lists with chainSample solution
# Merge two lists with chain
from itertools import chain
result = list(chain([1, 2], [3, 4]))
print(result)Expected output
[1, 2, 3, 4]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which module does chain come from?
- functools
- collections
- itertools Correct answer
- typing
Explanation: chain is in the itertools module.
2 chain import line
from itertools import ____
result = list(chain([1, 2], [3, 4]))
print(result)
from itertools import chain
result = list(chain([1, 2], [3, 4]))
print(result)
Explanation: chain is imported from the itertools module.
3 Match the chain parts
| Term | Meaning |
|---|---|
chain |
Combine function |
[1, 2], [3, 4] |
Two iterables |
list(...) |
List the result |
from_iterable |
Dynamic flatten |