Junior — Middle
Can you explain what happens when a generator function is called in programming?
sobes.tech AI
Answer from AI
When calling a generator function in Python, the function itself does not execute immediately in full. Instead, it returns a generator object that can be iterated over. Each time you iterate, the function resumes execution from where it was paused (after the yield statement) and returns the next value. This allows efficient handling of large sequences without loading the entire collection 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)
Here, count_up_to is a generator that returns numbers from 1 to 5 one by one.