10 Practical Scenarios Demonstrating Lazy Evaluation and Infinite Sequence Handling in Python
This article presents ten practical Python examples illustrating lazy evaluation using generators and iterators, covering infinite sequences, large data processing, file streaming, and on-demand computation, highlighting memory efficiency and performance benefits for handling big data and infinite streams.
Lazy evaluation is a key concept in functional programming where computation is deferred until the result is needed, offering advantages for infinite sequences and large‑scale data. Generators and iterators are common tools to achieve this. Below are ten practical Python scenarios that showcase lazy evaluation and infinite‑sequence handling.
1. Generate Fibonacci sequence
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for i in range(10):
print(next(fib)) # 输出: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34Using a generator function, we can produce an infinite Fibonacci sequence without pre‑computing all values.
2. Generate infinite natural numbers
def natural_numbers():
n = 1
while True:
yield n
n += 1
numbers = natural_numbers()
for i in range(10):
print(next(numbers)) # 输出: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10The generator yields an unbounded stream of natural numbers.
3. Use generator expression for large data
data = [1, 2, 3, 4, 5, ...] # 大规模数据
result = (x * 2 for x in data if x % 2 == 0)
for value in result:
print(value)Generator expressions produce each result on‑the‑fly, avoiding loading the entire dataset into memory.
4. Lazy read large file
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line
lines = read_large_file('large_file.txt')
for line in lines:
process_line(line)This reads a file line‑by‑line, keeping memory usage low.
5. Generate infinite squares
squares = (x**2 for x in natural_numbers())
for i in range(10):
print(next(squares)) # 输出: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100Generator expressions can create an infinite sequence of squared numbers.
6. Lazy prime filtering
def primes():
primes_list = []
yield 2
for n in natural_numbers():
if all(n % p != 0 for p in primes_list):
primes_list.append(n)
yield n
prime_gen = primes()
for i in range(10):
print(next(prime_gen)) # 输出: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29The generator produces prime numbers on demand, computing only what is required.
7. Lazy computation of the n‑th Fibonacci number
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
fib_n = fibonacci(10) # 只计算第10项
print(fib_n) # 输出: 55Only the requested term is calculated, avoiding full sequence generation.
8. Lazy processing of infinite sequence elements
def process_infinite_sequence(seq):
for item in seq:
process_item(item)
if should_stop(item):
break
infinite_seq = natural_numbers()
process_infinite_sequence(infinite_seq)The loop processes elements until a stopping condition is met.
9. Lazy chunked processing of large data
def process_large_data(data):
chunk_size = 1000
for i in range(0, len(data), chunk_size):
chunk = data[i:i+chunk_size]
process_chunk(chunk)
large_data = [1, 2, 3, 4, 5, ...] # 大规模数据
process_large_data(large_data)Data is handled in manageable chunks, reducing memory pressure.
10. Lazy accumulation of an infinite sequence
def accumulate(seq):
total = 0
for item in seq:
total += item
yield total
numbers = natural_numbers()
accumulated = accumulate(numbers)
for i in range(10):
print(next(accumulated)) # 输出: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55This yields the running sum of an infinite sequence on demand.
These examples demonstrate how generators and iterators enable lazy evaluation, allowing developers to handle infinite streams and massive datasets efficiently while conserving memory and computational resources.
Feel free to ask further questions to deepen your understanding of lazy evaluation and its practical benefits.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.