Beginner LevelPython
What is a Generator function and how does the `yield` keyword work?
❓ Interview Prompt: Explain Generator functions, `yield` keyword, state suspension, iterator protocol, and memory efficiency.
A Generator Function uses the 'yield' keyword instead of 'return':
How 'yield' Works:
•
When called, a generator function does NOT execute immediately; it returns a generator iterator object.
•
Every time 'next(gen)' or a 'for' loop is invoked, execution runs until it hits 'yield'. It yields the value and freezes/suspends execution state (local variables) right at that line!
•
When called again, execution resumes immediately after 'yield'.
Code Implementation Example
python
def fibonacci_generator(limit):
a, b = 0, 1
count = 0
while count < limit:
yield a # Suspends execution and returns value
a, b = b, a + b
count += 1
# Stream infinite/large Fibonacci sequence with minimal RAM!
for num in fibonacci_generator(5):
print(num, end=' ') # Output: 0 1 1 2 3💡Generating Fibonacci numbers lazily using yield.
🎯 Interview Key Takeaway
Generator functions suspend state at yield, streaming sequence items lazily without loading entire collections into memory.
#Generators#yield#Iterators#Beginner
Back to all Python Questions→