9.1. Iterator About

  • Lazy Evaluation

  • Values are computed on demand

  • No need to store all values in memory

  • Generator-like - behaves similarly, but is not a generator

iterable

An object supporting iteration. To create iterable class must implement Iterable protocol, to has __iter__() method.

iterator

An iterable object. To create iterator class must implement Iterator protocol, to has __iter__() and __next__() method.

9.1.1. Examples

  • reversed(sequence, /)

  • range(start=0, stop, step=1), count

  • enumerate(iterable, start=0)

  • zip(*iterables, strict=False), zip_longest

  • map(func, iterables*), starmap

  • filter(func, iterable)

  • chain(*iterables)

  • permutations(iterable, r=None)

  • product(*iterables, repeat=1)

  • cycle(iterable, /)

9.1.2. Inspect

  • from inspect import isgeneratorfunction

  • from inspect import isgenerator

>>> from inspect import isgeneratorfunction, isgenerator
>>>
>>>
>>> isgeneratorfunction(range)
False
>>>
>>> result = range(0,3)
>>> isgenerator(result)
False