If McDonalds were run like a software company, one out of every hundred Big Macs would give you food poisoning, and the response would be, “We’re sorry, here’s a coupon for two more.”
Hey pips!
Have you heard of the any
and all
builtin Python functions? They’re used to check the truthiness of items in an iterable.
any
returns True
if 1 or more of the objects are truthy:
>>> items = [0, None, False, ""]
>>> any(items)
False
>>> items.append("huzzah!") # we now have 1 truthy element!
>>> any(items)
True
all
returns True
if every object is truthy:
>>> items = ["noob", "master", 69]
>>> all(items)
True
>>> items.append(None) # we now have 1 falsy element!
>>> all(items)
False
This makes sense pretty intuitively, right?
>>> slots_available = [0, 0, 0, 0, 1, 0, 0]
>>> if any(slots_available):
print("booking the slot")
>>> people_available = ["bob", "rob", "sob", "mob", None, None]
>>> if all(people_available):
print("inviting everyone")
Giving variables and functions fitting names does wonders for readability 🔥
any
and all
come in super handy when combined with list comprehensions. They give us a very pythonic way to check if a condition is met for objects in an iterable:
>>> scores = [20, 40, 1, 16, 50, 32]
# are any of them odd?
>>> any([n % 2 == 1 for n in primes])
True
# are all of them positive?
>>> all([n > 0 for n in primes])
True
And of course, we can negate them to unlock even more logical tests!
>>> frameworks = ["numpy", "scipy", "keras", "pygame"]
>>> not all([len(framework) == 5 for framework in frameworks])
True
# although actually, this is identical!
>>> any([len(framework) != 5 for framework in frameworks])
True
Which of these is more suitable depends on context, as always.
not all(condition for each in list) == any(not condition for each in list)
not any(condition for each in list) == all(not condition for each in list)
Pick whichever makes most sense!
Given a list of integers, can you check if every number is greater than the number before it? (Is it a strictly increasing sequence?)
>>> n = [1, 2, 4, 7, 12, 67]
>>> (your_expression)
True
>>> n = [61, 52, 63, 94, 46]
>> (your_expression)
False
>>> n = [-1, 0, 1, 2, 2]
>>> (your_expression)
False
# 2 is not greater than 2
![Tip] You may need the ternary conditional!