Quick answer: yield turns a function into a generator. Instead of
returning once and exiting, the function pauses at each yield, hands back a value, and resumes
exactly where it left off the next time it's asked for another value.

A minimal example
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
What actually happens when you call it
Calling count_up_to(3) does not run the function body. It immediately
returns a generator object. Execution only begins when you iterate it (with a for loop, or by
calling next()). Each yield suspends the function, and the next
next() call resumes right after that yield, with all local variables intact.
Why use yield instead of returning a list?
# Builds the whole list in memory first
def squares_list(n):
return [i * i for i in range(n)]
# Produces one value at a time, lazily
def squares_gen(n):
for i in range(n):
yield i * i
The generator version never holds more than one value in memory at once, which matters enormously when
n is huge, or when the sequence is infinite (e.g. reading lines from a massive file or an
endless stream).
FAQ
Does a generator run the whole function immediately?
No. It runs lazily, one step per next() call, stopping at each yield.
When does a generator stop?
When the function returns (implicitly or via return) or runs off the end, Python raises
StopIteration, which loops handle automatically.
Is yield the same as return?
No. return ends the function permanently. yield pauses it, preserving state
for the next resume.
This article explains and expands on the community answers to the Stack Overflow question “What does the "yield" keyword do in Python?”, used under the CC BY-SA 4.0 license. Screenshot credit: Stack Exchange Inc.
No comments
Post a Comment