10.6. Iterator Chain

  • Lazy evaluated

  • itertools.chain(*iterables)

10.6.1. Solution

>>> 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.2. 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.3. 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.4. 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.5. 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