Junior — Middle
Explain the meaning of the yield operator in Python and how it is used in generators.
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 or used in a for loop, the function resumes execution from the last yield, returning the next value.
This allows efficient handling of large or infinite sequences without loading the entire collection into memory.
Example of a generator with yield:
def count_up_to(max_value):
count = 1
while count <= max_value:
yield count
count += 1
for number in count_up_to(5):
print(number)
Output:
1
2
3
4
5
Thus, yield enables the creation of lazy iterators, saving resources and simplifying code for sequential data processing.