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.
Iterators evaluate elements on demand rather than computing everything upfront. This is critical when working with large files, network streams, or infinite sequences.
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
File objects are already iterators in Python — iterating them is memory-efficient by default.