Build an Endless Fibonacci Stream with Python Generators
Math & Bit ManipulationModel answerLast updated
Explain how lazy evaluation works in Python and write a generator that yields Fibonacci numbers indefinitely, with safe ways to consume it and the reasoning behind its state handling.
Task
Two parts:
- In your own words, explain what lazy evaluation means in Python. Mention at least one built-in or language feature that behaves lazily, and contrast it with an eager equivalent.
- Write a generator function, using
yield, that produces the Fibonacci sequence without end:0, 1, 1, 2, 3, 5, 8, ...
Expectations
- The function must take no arguments and must not build a list of earlier terms.
- Each value should be computed only when the caller asks for the next one.
- Demonstrate how you would safely read:
- the first 10 terms,
- every term below 100,
- the term at index 1000 (0-indexed).
- Explain where the generator keeps its state between two consecutive requests.
- State the time and space cost of producing the first
nterms. - Mention which pitfalls apply when a caller consumes an infinite generator.
Expected outputs
- First 10 terms:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] - Terms below 100:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Hints
Hint 1
Think about what a Fibonacci step needs to remember. Two numbers are enough, so the generator only needs two local variables and an infinite loop.
Hint 2
A generator function does not run when called. It returns an iterator, and each `next()` resumes the body until the next `yield`, keeping its local variables alive in between.
Hint 3
Use tuple assignment, `a, b = b, a + b`, so both new values are computed from the old ones. To bound an infinite stream, use `itertools.islice` or `takewhile` rather than `list()` on the whole thing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What lazy evaluation means
Lazy evaluation means a value is produced at the moment it is needed, not in advance. In Python the mechanism is the iterator protocol: an object with __next__ that returns the next value on demand and raises StopIteration when it is exhausted.
Eager versus lazy:
- Eager:
[x * x for x in range(10**8)]allocates 100 million integers before you can read the first. - Lazy:
(x * x for x in range(10**8))returns instantly. Each square is computed only when something callsnext().
Lazy in Python 3: range, map, filter, zip, enumerate, generator expressions and most of itertools.
Why it matters:
- Infinite sequences fit in finite memory.
- Streaming: large files or feeds are processed in constant memory.
- Short-circuiting: if the consumer stops early, unrequested work is never done.
How generators keep state
A function containing yield is a generator function. Calling it does not execute the body; it returns a generator object (an iterator). Each next():
- resumes the body where it last paused,
- runs to the next
yield, - hands that value to the caller and suspends.
While suspended, the entire frame survives: local variables, the position in the code and the loop state. That frame is the state storage, so no globals or instance attributes are needed.
For Fibonacci the state is just the current pair (a, b).
Solution
from itertools import islice, takewhile
from typing import Iterator
def fib_stream() -> Iterator[int]:
"""Yield 0, 1, 1, 2, 3, 5, ... without end."""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
if __name__ == "__main__":
g = fib_stream()
print(next(g), next(g), next(g)) # 0 1 1
print(list(islice(fib_stream(), 10)))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
print(list(takewhile(lambda x: x < 100, fib_stream())))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print(next(islice(fib_stream(), 1000, None))) # term at index 1000
Why it is correct
Invariant: just before the k-th yield (k from 0), a == F(k) and b == F(k+1).
- Base:
a, b = 0, 1givesF(0), F(1). - Step: after yielding
F(k),a, b = b, a + bgivesa = F(k+1)andb = F(k) + F(k+1) = F(k+2).
The tuple assignment evaluates the whole right-hand side before rebinding either name. Writing a = b then b = a + b is a classic bug: it computes b + b.
Why the infinite loop is safe: while True never runs by itself. It advances one iteration per next() and freezes at yield. The caller decides how far it goes, usually through islice or takewhile.
You can observe laziness directly: add a print before the yield, call fib_stream() and do not iterate. Nothing is printed.
Complexity
- Time: O(1) additions per term, so O(n) additions for n terms. Strictly, F(n) has about 0.694·n bits and each big-integer addition is linear in bit length, so the bit-level cost for n terms is O(n²).
- Space: O(1) Python objects (two integers and one suspended frame), versus O(n) for a list. In bits, the live numbers take O(n).
Pitfalls and edge cases
- Consuming it whole.
list(fib_stream()),sum(...)andmax(...)never finish and eventually exhaust memory. Always bound it withislice,takewhile,zipagainst a finite iterable, or abreak. - Single pass. A generator does not replay. Call
fib_stream()again for a fresh, independent sequence; each call has its own frame. - Starting convention. This version starts at
0, 1. If a spec wants1, 1, initializea, b = 1, 1. Always state the convention. - Overflow. Python ints are arbitrary precision, so no overflow. In languages with 64-bit signed integers, F(93) overflows.
- Avoid recursion. Naive recursive
fib(n)is exponential and hits the recursion limit. The generator is iterative with constant stack use. - Index vs. count.
islice(it, 1000, None)skips 1000 items, sonexton it returns the term at index 1000, not the 1000th term counting from 1.
Same behaviour as an iterator class
Without yield, you would hand-write the protocol and store state on self:
class FibIterator:
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
value = self.a
self.a, self.b = self.b, self.a + self.b
return value
Both behave identically. The generator is shorter because Python suspends and resumes the frame for you.
Worthwhile extensions
- Pipelines stay lazy:
filter(lambda x: x % 2 == 0, fib_stream())yields even Fibonacci numbers on demand. yield fromdelegates to a sub-generator.send()lets a caller push values into a generator, enabling coroutine-style code (for example, a reset signal).- Jumping far ahead: if you only need F(n) for large n and not the stream, fast doubling computes it in O(log n) arithmetic operations, whereas skipping through the generator is O(n).