Iteration and Generators

Iteration in Python

What's an Iterator?

An iterator is an object that yields a data stream ...

Question: where do iterators come from?

Answer: they are made by iterables

What's an Iterable?

Iterables are objects that support iteration (Gosh!)

Iterables that are built into Python are for example ...

The Iterator Protocol (1)

Technically speaking ...

for elem in iterable:
    ... do something with elem ...

The interpreter ...

The Iterator Protocol (2)

iterator = iter(iterable)
try:
    i = next(iterator)
except StopIteration:
    ...

Generators: Motivation

Examples of complicated iteration ...

Stupid solution:

Generators: How?

def odd_numbers():
    i = 0
    while True:
        if i%2 != 0:
            yield i
        i += 1

for j in odd_numbers():
    print(j)

Observations

More on Generators

Python 2 to 3 transition

Standard library helpers