Write a generator function that yields Fibonacci numbers indefinitely
py-jun-002
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
A generator function uses yield to lazily produce values on demand rather than computing them all upfront. I track the last two numbers in local variables and yield each new value in an infinite while loop. The caller controls when to stop using itertools.islice, a for loop with break, or next(). Generators are memory-efficient for infinite sequences: only two integers reside in memory regardless of how many values have been consumed.
Code example
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Take first 10 Fibonacci numbers
print(list(islice(fibonacci(), 10)))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Or consume lazily
for n in fibonacci():
if n > 100:
break
print(n)
Follow-up
How does a generator differ from a list comprehension in memory usage? When would you use 'yield from' to delegate to another generator?