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.
Filtering: loop with if vs comprehension vs filter()
Keep the delivered Online Store orders over $100 and show their IDs.
what differs
All keep the same rows in the same order. filter() returns an iterator that does nothing until consumed; filter(None, items) keeps only truthy items.
at a glance
| approach | use it when |
|---|---|
| A · loop with if | The condition needs several steps or you're also doing something else per row. |
| B · comprehension | Most of the time: the condition and the value to keep fit in one readable line. |
| C · filter() | You already have a named predicate to reuse, or you want a lazy filter in a pipeline. |
the outputs
Each approach runs on the same input.
concepts
filterpredicatecsv.DictReader
learn it
Build a dictionary with a comprehension · map and filter, or a comprehension?
related comparisons
for loop vs comprehension vs map() · Flags in a loop vs any() / all()