Utilizing Lazy Evaluation for Infinite Sequences
In this lesson, you will learn how to create "infinite" data structures in Python that exist without consuming all your computer's memory.
Normally, if you try to create a list of all integers, your program will crash because it tries to store an infinite number of items in RAM. Python solves this through lazy evaluation, where a value is only calculated at the exact moment the program asks for it, rather than all at once.
The Power of Generators
Because generator functions use the yield statement to pause execution, they are the perfect tools for defining infinite sequences. You define the logic for the next step, but the computer doesn't perform the calculation until you explicitly request the next item.
Consider this function that generates an infinite sequence of counting numbers:
def count_up():
num = 1
while True:
yield num
num += 1
# Create the generator object
counter = count_up()
# Request values one by one
print(next(counter)) # 1
print(next(counter)) # 2
print(next(counter)) # 3
In this code, count_up never actually finishes; it has no return statement that terminates the loop. However, because it is lazy, Python only keeps the current num in memory. It only calculates the next number when you call next() on the generator object.
Why Use This?
This pattern is incredibly powerful for scenarios where you need to process data streams or simulations where you don't know the stopping point ahead of time. You can chain these infinite sequences together, filter them, or map them using generator expressions, and Python will keep everything memory-efficient by only evaluating the "next" step on demand. You treat the infinite sequence like a faucet: it has an endless supply, but you only catch the water you need in your bucket.
Key Takeaway: Lazy evaluation allows you to define infinite data structures that consume a constant, minimal amount of memory by calculating values only when they are explicitly requested.