Python for Programmers: Any and All
Welcome to the Any and All lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Python comes with a pair of built-in functions for working with iterables, like lists or tuples, that contain booleans or other truthy and falsey values. The
anyfunction asks whether any value in an iterable is truthy.>
result = any(["a" + "b" == "abb","x" + "y" == "z",])resultResult:
False
>
account_balances = [-100, 200, 300]below_zero = [balance < 0 for balance in account_balances]overdraft_handling_required = any(below_zero)overdraft_handling_requiredResult:
True
anyasks whether at least one element is truthy. But if there are no elements, then there are no elements that are truthy.>
any([])Result:
False
The fact that
any([]) == Falsemay seem arbitrary at first, but it's not. Writing a simple implementation ofanyourselves shows why it works this way. We filter the list down to only the truthy values, then ask whether that list has any elements.>
def custom_any(values):truthy_values = [value for value in values if value]return len(truthy_values) > 0- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_any([True, False, True])Result:
True
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_any([False, False, False])Result:
False
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_any([])Result:
False
If you ever forget whether
any([])isTrueorFalse, think back to the implementation above!The
allfunction asks whether every value in an iterable is truthy.>
result = all([-3 <= 4,7 <= 10,2 == 2.0,])resultResult:
True
>
account_balances = [100, 200, -50]above_zero = [balance >= 0 for balance in account_balances]all_accounts_in_good_standing = all(above_zero)all_accounts_in_good_standingResult:
False
The
allfunction is true for empty iterables, which is the opposite ofany's behavior.>
all([])Result:
True
Once again, we can remember this by thinking about a simple implementation that filters the values.
>
def custom_all(values):truthy_values = [value for value in values if value]return len(truthy_values) == len(values)- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_all([True, True, True])Result:
True
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_all([True, False, True])Result:
False
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
custom_all([])Result:
True
When we call
custom_all([]), we're asking "is the number of truthy values the same as the original number of elements?" Both have 0 elements, so yes!anyandallwork with any iterable data type (any data type that we can use in aforloop).When we iterate over a dictionary with a
forloop, we get the dictionary's keys. Likewise, if we pass a dictionary toanyorall, we're asking "are any/all of this dictionary's keys (not values!) truthy?">
result = any({True: 100,False: 200,})resultResult:
True
>
result = any({False: 100,0: 200,})resultResult:
False
>
result = all({"a string": 100,"another string": 200,})resultResult:
True
Here's a code problem:
Write a function that decides whether a password meets all of our password requirements. We've already written functions that check three different validation rules. Each function returns a boolean.
You can solve this by calling
allon a list comprehension, where the list comprehension loops overvalidators, calling each one on the password. Don't forget to pass the password to each function!def at_least_4_characters(password):return len(password) >= 4def shorter_than_20_characters(password):return len(password) < 20def contains_special_characters(password):# `.isalnum()` is true when the string is "alphanumeric", meaning it only# contains letters and numbers.return not password.isalnum()validators = [at_least_4_characters,shorter_than_20_characters,contains_special_characters,]def password_allowed(password):return all([validator(password) for validator in validators])assert not password_allowed("abc")assert not password_allowed("hunter2")assert not password_allowed("no one will ever guess this long password!")assert password_allowed("M!lesP0wer")assert password_allowed("@HereYouGo@")- Goal:
None
- Yours:
None