Skip to content
Justice Tech School

Generators and yield

A generator function uses yield to produce values one at a time and saves memory. Generator expressions look like comprehensions in parentheses.

Example
def count(n):
    for i in range(n):
        yield i * i
print(list(count(4)))
g = (x for x in range(3))
print(next(g), sum(g))

Result

[0, 1, 4, 9]
0 3

Exercise

Produce a value.

 i

Quiz Test

What does yield do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.