Infinite Sequences and Lazy Evaluation
In this lesson, you will learn how to create and manage data streams that never end by calculating values only when they are requested.
The Power of "Not Yet"
So far, you’ve worked with structures like lists or tuples that occupy a fixed amount of memory the moment you create them. If you try to store an infinite series of numbers in a list, your computer will quickly run out of RAM and crash.
Lazy evaluation solves this by shifting the strategy: instead of pre-calculating and storing a collection, we write a recipe to generate the next item only when we need it. This allows us to represent "infinite" sequences because the system only ever holds a single value (or a tiny state) in memory at any given time.
Implementing an Infinite Stream
To create an infinite sequence, we use our knowledge of the iterator protocol (specifically the __next__ method) to provide a new value every time we ask for it, without ever triggering a StopIteration signal.
Consider this infinite generator for even numbers:
class EvenNumbers:
def __init__(self):
self.current = 0
def __iter__(self):
return self
def __next__(self):
value = self.current
self.current += 2
return value
# Usage:
evens = EvenNumbers()
print(next(evens)) # 0
print(next(evens)) # 2
print(next(evens)) # 4
In this example, the EvenNumbers object doesn’t contain a list of numbers. It contains a rule: "The next value is the current one plus two." Because we never raise StopIteration, we can call next() forever.
Why Use Lazy Evaluation?
This approach is incredibly efficient for data pipelines. Imagine processing a sensor that sends data every millisecond. You don’t want to store millions of readings in a list; you want to process one reading at a time as it arrives. By keeping the sequence lazy, your memory usage remains constant, regardless of whether you process ten items or ten billion.
Key Takeaway: Infinite sequences allow you to represent unbounded data streams by calculating values on demand, ensuring your programs remain memory-efficient even when dealing with massive or continuous data.