Tsallaka zuwa abun ciki
Justice Tech School

Generators

A function with yield is a generator. It pauses at each yield and continues from there on the next request, so it never needs to hold the whole result in memory. A generator expression looks like a list comprehension with parentheses.

Example
def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))

gen = (x * x for x in range(5))
print(next(gen), next(gen))
print(sum(x for x in range(101)))

Result

[3, 2, 1]
0 1
5050

Exercise

Produce a value from a generator.

def numbers():
     1

Quiz Test

What is the benefit of a generator?

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