all()
Introduction
The function all() returns True if all objects inside the iterable are True.
Otherwise it returns False
If the iterable is empty, then all() will return True
The function parameter can be an iterable
(
list
,
tuple, dictionary)
Syntax
all(iterable)
Example
The simplest example checking the whole list
t = [True, True, True] if all(t): print("only True")
only True
Example with numbers
my_list = [1, 2, 3] if all(my_list) > 0: print("all positive")
all positive
This result should not mislead you: if you add negative numbers to my_list, it will still be all positive
my_list = [1, -2, "some text"] if all(my_list) > 0: print("all positive")
all positive
In Python any number other than zero is interpreted as True.
all() iterates over all elements
- 1 → True
- -2 → True
- "some text" → True
Everything is True, so all() will also return True.
Checking a list
To check whether all numbers in the list are positive you need to use the function all() as well as, for example, map() and lambda
l1 = [1, 2, 3] l2 = [1, -2, "some text"] if all(map(lambda x: x > 0, l2)): print("all positive in l2") else: print("not all positive in l2") if all(map(lambda x: x > 0, l1)): print("all positive in l1") else: print("not all positive in l1")
all positive in l1
not all positive in l2
With generators
Let us examine the use of the function all() with generators .
print(any(is_prime(x) for x in range(1328, 1361))) print(any(is_prime(x) for x in range(99, 102))) print(all(is_prime(x) for x in range(99, 102))) print(all(name == name.title() for name in ['Benalmadena', 'Cordoba', 'Fuengirola', 'Malaga']))
False True False True
Article author: Andrei Olegovich