9.8. Iterator Chain
Lazy evaluated
itertools.chain(*iterables)
9.8.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
9.8.2. Use Case - 1
>>> from itertools import chain
>>>
>>>
>>> class Iterator:
... def __iter__(self):
... self._current = 0
... return self
...
... def __next__(self):
... if self._current >= len(self.values):
... raise StopIteration
... element = self.values[self._current]
... self._current += 1
... return element
>>>
>>>
>>> class Character(Iterator):
... def __init__(self, *values):
... self.values = values
>>>
>>>
>>> class Number(Iterator):
... def __init__(self, *values):
... self.values = values
>>>
>>>
>>> chars = Character('a', 'b', 'c')
>>> nums = Number(1, 2, 3)
>>> data = chain(chars, nums)
>>> next(data)
'a'
>>> next(data)
'b'
>>> next(data)
'c'
>>> next(data)
1
>>> next(data)
2
>>> next(data)
3