compare approaches one problem · three 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.
for loop vs comprehension vs map()
Build a list of the prices with 7% tax added.
what differs
All three build a new list. The loop names the empty list and appends; the comprehension describes the whole list in one expression and its variable doesn't leak out afterwards; map() returns a lazy iterator, so list() is needed to see the values.
at a glance
| approach | use it when |
|---|---|
| A · for loop | The body does more than compute one value: several statements, printing, try/except. |
| B · list comprehension | Turning one iterable into a new list with one expression and maybe one condition. |
| C · map() | You already have a named function to apply (map(str.upper, words)); with a lambda, the comprehension usually reads better. |
Watch out: A comprehension with two for clauses and two conditions is harder to read than the loop. map() over two iterables stops at the shorter one.
the outputs
Each approach runs on the same input.
concepts
list comprehensionmaplazy iterator
learn it
Build a list with a comprehension · A loop inside a loop
related comparisons
List vs generator: using it twice · Filtering: loop with if vs comprehension vs filter()