SyntaxStudy
Sign Up
Python Lazy Evaluation with Iterators
Python Intermediate 4 min read

Lazy Evaluation with Iterators

Lazy Evaluation

Iterators evaluate elements on demand rather than computing everything upfront. This is critical when working with large files, network streams, or infinite sequences.

Example
def read_large_file(path):
    with open(path) as f:
        for line in f:
            yield line.strip()

for line in read_large_file("huge.log"):
    process(line)  # one line in memory at a time
Pro Tip

File objects are already iterators in Python — iterating them is memory-efficient by default.