← Back to Python Course | Chapter 11: Advanced Python | Lesson 2 of 12

Python Generators

What is a Generator?

A generator function looks like an ordinary function but uses yield instead of return, and calling it doesn't run the function body immediately -- it returns a generator object that produces values one at a time only as they're requested.

Example: What is a Generator?

python
def my_gen():
    yield 1
    yield 2

g = my_gen()
print(type(g))
print(next(g))

The yield Keyword

Each time yield executes, the function pauses exactly there, hands back the yielded value, and remembers its entire local state (variables, position in loops) -- the next call to next() resumes execution right after that yield rather than starting the function over.

Example: The yield Keyword

python
def counter():
    n = 1
    while True:
        yield n
        n += 1

c = counter()
print(next(c))
print(next(c))

Generator Expressions

A generator expression -- (x*2 for x in range(10)) -- creates a generator with syntax almost identical to a list comprehension, but using parentheses instead of square brackets, and without ever building the full list of results in memory.

Example: Generator Expressions

python
squares = (x * x for x in range(5))
print(list(squares))

Generator State and Lifecycle

When a generator function runs off the end of its body or hits a plain return statement, Python automatically raises StopIteration to signal there's nothing left to produce -- this is exactly the same signal a for loop watches for when iterating any iterator.

Example: Generator State and Lifecycle

python
def one_value():
    yield "only value"

g = one_value()
print(next(g))
try:
    next(g)
except StopIteration:
    print("Generator exhausted")

Performance Benefits

Because a generator computes and yields one value at a time instead of building an entire list upfront, it uses a fixed, small amount of memory regardless of how many values it ultimately produces -- ideal for streaming through datasets too large to fit comfortably in RAM.

Example: Performance Benefits

python
import sys
list_version = [x for x in range(1000)]
gen_version = (x for x in range(1000))
print(sys.getsizeof(list_version) > sys.getsizeof(gen_version))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.