Today we’ll briefly discuss the two built-in functions: all and any. They are very handy and make our life easier, but these are again examples of something you could live without. There are other ways in Python of achieving the same results, as you are about to see.
Here’s the video version:
These two functions work on any iterable: a string, a list, a dictionary, a range, and so on.
The all Function
The all function can be thought of as a series of and operators. It returns True if all the elements in the iterable are True and False otherwise.
So, instead of using multiple and operators like this:
>>> 2 + 3 == 5 and 'a' in 'car' and 5 and True
True
we can use the all function. The function requires one argument, so we have to pass all the elements enclosed in a list or tuple for example:
>>> all([2 + 3 == 5, 'a' in 'car', 5, True])
True
The any Function
The any function can be thought of as a series of or operators. It returns True if any of the elements in the iterable is True and False otherwise.
So, instead of using multiple or operators like this:
>>> len("hi") > 10 or 0 or 3 ** 2 == 9 or 'abc'[0] == 'a'
True
we can use the any function. The function also requires one argument, so we have to pass all the elements enclosed in a list or tuple again, for example:
>>> any([len("hi") > 10, 0, 3 ** 2 == 9, 'abc'[0] == 'a'])
True
Short-Circuited Execution with all and any
Both all and any short-circuit the execution. As soon as it’s known what the result will be, the other elements in the iterable are omitted. For example in the following code:
>>> all((3, 0, 4, 7, 3, 8))
False
The execution will be short-circuited at the second element because at this moment it’ll be clear that the result is False.
Similarly, in the following code:
>>> any([0, False, '', 2, 1 > 2, [], {}, None, True])
True
execution will be short-circuited at the element 2, because if at least one element is True, the result is True. By the way, all non-zero and non-empty objects are regarded as True.
We can use any iterables. Comprehensions also return iterables, so they can be used:
words = ['cat', 'car', 'cliff', 'color', 'cow']
>>> all(word.startswith('c') for word in words)
True
>>> any(len(word) > 3 for word in words)
True