Advertisement
Beginner Python, Comprehensions & Generators

What is a generator function, and how does 'yield' make it different from a regular function?

Short answer

A generator function contains at least one 'yield' statement; calling it doesn't run the function body immediately — it returns a generator object, and the body only executes incrementally, one step at a time, each time you request the next value (via next() or a for loop).

Save Python mock interview
Advertisement
AModel answer
A generator function contains at least one 'yield' statement; calling it doesn't run the function body immediately — it returns a generator object, and the body only executes incrementally, one step at a time, each time you request the next value (via next() or a for loop).
def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for number in count_up_to(3):
    print(number)  # 1, 2, 3
Real-world example
Lazily producing a sequence of values one at a time instead of building and returning a full list upfront.
Likely follow-ups
  • What exception is raised internally when a generator is exhausted and next() is called again?
Related topics