×

python · level 3 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A hands out values one at a time with .

Put yield in a function and it becomes a generator. Calling it runs nothing yet: it gives you an iterator. Each next() runs the code up to the next yield, hands out that value, then pauses right there.

Generators are , so they only work when asked. One can read a huge log line by line, or count forever, without ever holding everything in memory.

A is a comprehension in round brackets. sum(n * n for n in range(4)) adds up the squares without building a list first.

def countdown(start):
    while start > 0:
        yield start
        start = start - 1
    yield "Lift off!"

for step in countdown(3):
    print(step)
print(sum(n * n for n in range(4)))

When a generator's code reaches the end, it raises StopIteration for you.