Junior — Middle
What is the role of the yield operator in Python, and how does it affect function execution?
sobes.tech AI
Answer from AI
The yield operator in Python is used inside functions to create generators — special iterators that return values one at a time, maintaining their state between calls.
When a function with yield is called, it does not execute fully but returns a generator. Each time the __next__() method is called, the generator resumes execution of the function until the next yield, returning a value and pausing execution.
This allows efficient handling of large volumes of data without loading it entirely into memory.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
In this example, the count_up_to function returns numbers from 1 to n one at a time using yield. This saves memory and allows processing data as needed.