10.6. Iterator Chain — Python
Lazy evaluated
itertools.chain(*iterables)
10.6.1. SetUp
>>> from itertools import chain
10.6.2. Problem
>>> def a(): ... yield 'Alice' ... yield 'Bob' ... yield 'Carol' >>> >>> def b(): ... yield 'Dave' ... yield 'Eve' ... yield 'Mallory' >>> >>> >>> result = a() + b() Traceback (most recent call last): TypeError: unsupported operand type(s) for +: 'generator' and 'generator'
10.6.3. Solution
>>> from itertools import chain >>> >>> >>> def a(): ... yield 'Alice' ... yield 'Bob' ... yield 'Carol' >>> >>> def b(): ... yield 'Dave' ... yield 'Eve' ... yield 'Mallory' >>> >>> >>> result = chain(a(), b()) >>> >>> list(result) ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
10.6.4. Iteration
>>> def a(): ... yield 'Alice' ... yield 'Bob' ... yield 'Carol' >>> >>> def b(): ... yield 'Dave' ... yield 'Eve' ... yield 'Mallory' >>> >>> >>> for name in chain(a(), b()): ... print(name) Alice Bob Carol Dave Eve Mallory
10.6.5. Example
>>> from itertools import chain >>> >>> >>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3] >>> >>> for x in chain(keys, values): ... print(x) a b c 1 2 3
10.6.6. Use Case - 1
>>> from itertools import chain >>> >>> >>> def a(): ... yield 1 ... yield 2 ... yield 3 >>> >>> def b(): ... yield 10 ... yield 20 ... yield 30 >>> >>> >>> data = chain(a(), b()) >>> >>> next(data) 1 >>> >>> next(data) 2 >>> >>> next(data) 3 >>> >>> next(data) 10 >>> >>> next(data) 20 >>> >>> next(data) 30 >>> >>> next(data) Traceback (most recent call last): StopIteration
10.6.7. Use Case - 2
>>> def square(x): ... return x ** 2 >>> >>> def cube(x): ... return x ** 3 >>> >>> >>> data = [1, 2, 3] >>> >>> result = chain( ... map(square, data), ... map(cube, data) ... ) >>> >>> for x in result: ... print(x) ... 1 4 9 1 8 27
10.6.8. Use Case - 3
>>> from pathlib import Path >>> >>> >>> files = Path('/tmp').rglob('*.txt') >>> >>> files <map object at 0x104b6e560> >>> >>> sorted(files) [PosixPath('/tmp/myfile1.txt'), PosixPath('/tmp/myfile2.txt'), PosixPath('/tmp/myfile3.txt')]
10.6.9. Use Case - 4
>>> from pathlib import Path >>> >>> >>> mydir = Path('/tmp') >>> >>> files = chain( ... mydir.rglob('*.txt'), ... mydir.rglob('*.csv'), ... mydir.rglob('*.json'), ... ) >>> >>> for file in sorted(files): ... print(file.name) ... myfile1.csv myfile1.json myfile1.txt myfile2.csv myfile2.json myfile2.txt myfile2.json myfile3.txt
10.6.10. Assignments
# %% About # - Name: Iterator Chain Generators # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Chain `DATA1` and `DATA2` into a single sequence # 2. Define variable `result: list[str]` with the solution # 2. Run doctests - all must succeed # %% Polish # 1. Połącz (`chain`) `data1()` i `data1()` w jedną sekwencję # 2. Zdefiniuj zmienną `result: list[str]` z rozwiązaniem # 2. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> list(result) # ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is chain, \ 'Variable `result` has an invalid type; expected: `list`.' >>> list(result) ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from typing import Iterator from itertools import chain # %% Types result: Iterator[str] # %% Data def data1(): yield 'Alice' yield 'Bob' yield 'Carol' def data2(): yield 'Dave' yield 'Eve' yield 'Mallory' # %% Result result = ...
# %% About # - Name: Iterator Chain Sequence # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Chain `DATA1` and `DATA2` into a single sequence # 2. Define variable `result: list[str]` with the solution # 2. Run doctests - all must succeed # %% Polish # 1. Połącz (`chain`) `DATA1` i `DATA2` w jedną sekwencję # 2. Zdefiniuj zmienną `result: list[str]` z rozwiązaniem # 2. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> list(result) # ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is chain, \ 'Variable `result` has an invalid type; expected: `list`.' >>> list(result) ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from typing import Iterator from itertools import chain # %% Types result: Iterator[str] # %% Data DATA1 = ['Alice', 'Bob', 'Carol'] DATA2 = ['Dave', 'Eve', 'Mallory'] # %% Result result = ...