compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
List vs generator: using it twicebehaves differently
Compute squared errors, then use them twice (total and maximum).
what differs
The list stores all values and can be read again. The generator computes values on demand and is exhausted after sum() consumes it, so max() sees nothing and returns the default.
at a glance
| approach | use it when |
|---|---|
| A · list comprehension | You'll use the values more than once, index them or need len(). |
| B · generator expression | One pass over a large or unbounded sequence, where memory matters. |
Watch out: Without default=None, max() of an empty iterator raises ValueError, which is how this bug usually shows up.
the outputs
Each approach runs on the same input.
concepts
lazy evaluationexhaustionmemory
learn it
Lazy pipelines: generator expressions, islice and takewhile
related comparisons
Iterator class vs generator function · read() vs readlines() vs iterating the file