Skip to main content

Iterators and Generators

Generator Expressions

0:00
LearnStep 1/3

Mastering Generator Expressions

Generator expressions provide a concise, memory-efficient way to create generators. They look similar to list comprehensions but use parentheses () instead of square brackets []. Unlike list comprehensions, which generate the entire list in memory immediately, generator expressions yield items one by one using lazy evaluation.

Syntax Comparison

python

Memory Efficiency

The primary advantage is memory usage. If you are processing a large dataset (e.g., 1 million records) and only need to iterate over the results once (or reduce them to a single value), a generator expression is superior.

python

Passing to Functions

You can pass generator expressions directly to functions like sum(), min(), max(), or any() without extra parentheses.

python

Common Gotchas: One-Time Use

Remember that generators are exhausted after iteration. You cannot iterate over them twice.

python