Compare a lazy generator expression with a list comprehension.
What You Will Learn
A list comprehension produces a list immediately; a generator expression produces values when iterated. Generator expressions can save memory but are consumed and may observe external state later.
Choose a list when you need reuse or random access; choose a generator for one-pass iteration.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
numbers = range(1, 6)
list_squares = [number ** 2 for number in numbers]
generator_squares = (number ** 2 for number in numbers)
print(list_squares)
print(next(generator_squares))
print(list(generator_squares))
How the Example Works
- The variable numbers holds the result of range(1, 6). Later lines use that value or inspect how it changes.
- The variable list_squares holds the result of [number ** 2 for number in numbers]. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
[1, 4, 9, 16, 25]
1
[4, 9, 16, 25]
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Create both forms from a large range and compare their types.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming a generator expression can be indexed like a list.
- Consuming the generator once and expecting it to produce the same values again.
Key Takeaways
- Compare a lazy generator expression with a list comprehension.
- A list comprehension produces a list immediately; a generator expression produces values when iterated.
- Choose a list when you need reuse or random access; choose a generator for one-pass iteration.