Legends ofPythos
Claim your name
Pythonic Python

Generators and yield

Lesson 3 of 12

Watch the lesson5:45 · with Sigrid
A generator works like a ticket machine at a stadium: instead of printing all tickets for ten thousand fans at once, it prints one when you ask and waits until you request the next. In Python, this means using yield inside a function to pause execution and hand back values one at a time.

The Mental Model

def count_up(n):
    for i in range(1, n + 1):
        yield i

g = count_up(3)
print(next(g))  # 1, then pauses at yield
print(next(g))  # 2: carries on from the pause
print(list(g))  # [3]: the rest of the loop
count_up hands over one value at a time, pausing at each yield.
Notice that count_up returns a generator object, not the numbers themselves. The code inside does not run until you ask for values by calling next() or looping over it. This is lazy evaluation: work happens only when needed.

In count_up, range(1, n + 1) counts from 1 up to n: a range stops just before its second number, so the + 1 takes it up to n itself. A range can also take a third number, the step: how much to count up by each time. range(10, 40, 10) gives 10, 20 and 30.

Why Lazy Evaluation Matters

def temp_readings(n):
    # Imagine reading from a slow sensor
    for i in range(1, n + 1):
        yield 20.5 + (i * 0.1)

total = sum(temp_readings(5))
print(total)
A lazy sequence for temperature logs.
The example above added up the readings without ever storing all five at once. That matters for big jobs, such as a log file with millions of lines: a list of every line could use a lot of memory, while a generator holds one line at a time.

Generator Expressions

You can write a one-line generator using round brackets ( ) instead of square brackets [ ]. It looks like a list comprehension, but it makes its values one at a time, when asked. That's handy when you only pass the values on, for example to sum(), and never need the whole list.
# Eager: creates [1, 4, 9] in memory
squares_list = [x * x for x in range(1, 4)]
print(squares_list)

# Lazy: produces values one by one on demand
lazy_squares = (x * x for x in range(1, 4))
print(next(lazy_squares)) # Prints 1
print(list(lazy_squares)) # Prints [4, 9]
Lazy squares vs eager list.
def one_shot():
    yield "first"
    yield "second"

seq = one_shot()
print(list(seq)) # ['first', 'second']
print(list(seq)) # [] - Empty! It's exhausted.
Single-use nature of generators.

Your turn

0 of 3 solved

Exercise 1

+40 XP
Write a generator function called evens(n) that lazily yields every even number from 2 up to and including n (inclusive). It should yield nothing if n < 2.

Hint: range(2, n + 1, 2) counts from 2 in steps of 2: its third number is the step. It stops before n + 1. Or loop over every number and check i % 2 == 0.
def evens(n):
    pass

Run your code to check it against the tests.

Exercise 2

+40 XP
Write a generator function called take(n, iterable) that lazily yields at most the first n items from any iterable (list, range, another generator). If n is 0 or negative it should yield nothing.

Hint: loop with for item in iterable and keep a counter. Check the count before each yield, and break once it reaches n.
def take(n, iterable):
    pass

Run your code to check it against the tests.

Exercise 3

+40 XP
Create a generator expression (round brackets, not square) called lazy_squares that produces the squares of 1 to 50. Then add them up into total and print it.
Write your Python here.

Run your code to check it against the tests.