runtime

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

approachuse it when
A · loop with ifThe condition needs several steps or you're also doing something else per row.
B · comprehensionMost 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()

Uses the Online Store dataset.

A · loop with if
B · comprehension
C · filter()
Compare Python Approaches · Runtime