Middle
What is the yield keyword and how is it used in Python?
sobes.tech AI
Answer from AI
The keyword yield is used in Python to create generators.
A generator is a function that returns an iterator. Instead of returning all values at once (like a regular function), a generator "yields" values one at a time using yield, while maintaining its internal state between calls.
Main advantages of using generators with yield:
- Memory efficiency: Generators do not store the entire sequence in memory but compute elements "on the fly." This is especially useful when working with large data volumes.
- Lazy evaluation: Values are generated only when they are actually needed (during iteration).
- Code simplicity: Generator code is often more readable and compact compared to explicitly defining an iterator class.
How it works:
- When a function with
yieldis called, it does not execute immediately but returns a generator object. - On the first call to
next()for the generator (for example, in aforloop), the function's code runs up to the firstyieldstatement. The value to the right ofyieldis returned. The function's state (local variables and where it stopped execution) is saved. - On subsequent
next()calls, execution resumes exactly from where it left off after the previousyield. - This continues until the function completes normally or encounters a
returnstatement without a value (or an emptyreturn). In this case, aStopIterationexception is raised, signaling the end of the sequence.
Example:
# A simple generator that generates numbers up to n
def count_up_to(n):
i = 0
while i < n:
yield i # Yield the current value
i += 1
Using the generator:
# Create a generator object
counter = count_up_to(5)
# Iterate over the generator
print(next(counter)) # Output: 0
print(next(counter)) # Output: 1
# Using in a for loop
for num in count_up_to(3):
print(num)
# Output:
# 0
# 1
# 2
yield can also be used to receive values from outside the generator using the send() method, allowing the creation of coroutines, but this is a more advanced usage scenario.