runtime

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.

Flags in a loop vs any() / all()

Is any reading negative, and are all readings below 100?

what differs

any() stops at the first True and all() at the first False, so they can skip most of the data. The loop always looks at everything (it could break, but then can't track both facts).

at a glance

approachuse it when
A · loop with flagsYou need several facts from one pass, or the reason as well as the answer.
B · any() and all()Asking one yes/no question about a collection.

Watch out: all([]) is True and any([]) is False: an empty list has no counter-example.

the outputs

Each approach runs on the same input.

concepts

short-circuitgenerator expression

learn it

Ask about the whole collection with any and all

related comparisons

Filtering: loop with if vs comprehension vs filter()

A · loop with flags
B · any() and all()
Compare Python Approaches · Runtime