Hone

Lessons · Python · any() and all()

Asking a question of every item at once

any() asks 'is at least one true?', all() asks 'are they all true?', over a whole list in one line.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Validation is full of these: does any field contain an error, are all boxes ticked, has every server reported in.

How to think about it

Is the sentence 'is there any...' or 'are all...'? Say the sentence in English first. If it starts 'is there any...' reach for any(); 'are all...' reach for all(). Then write the condition for one item and let the function do the loop.

Worked example

temps = [18, 21, 35, 19]
Four readings. We want to know whether any is over 30.
hot = any(t > 30 for t in temps)
For each t, the condition t > 30. any() stops the moment it finds a True.
print(hot)
True, because of the 35.
print(all(t > 15 for t in temps))
all() would stop at the first False; here every reading is over 15, so True.

Your turn

Check whether every name in a list is non-empty.

names = ["Ada", "", "Cy"]
ok = (len(n) > 0 for n in names)

The trap

all() of an EMPTY list is True and any() of an empty list is False. Reasonable once you think about it, surprising the first time.

Practise any() and all() on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.