How do Python's any and all functions work?

any and all take iterables and return True for the following scenario.

  1. all : The all function returns true if all elements in an iterable are true. False otherwise.
  2. any : The any function returns true if any element in an iterable is true. False otherwise.

The syntax of all() and any() method are: 

all(iterable)
any(iterable)

Both the methods take an iterable (list, string, dictionary etc.) in Python. The all() method returns for an Empty iterable, where as the any() method returns false for an Empty iterable. Following is the truth table for these methods.

Following are some example of usage of all() method for a List.

>>> list = [10,20,33,2]
>>> all(list)
Output : True

The output of the above program is True. As the list does not have any Zero (0). The result will be False , if the list contains any 0, as Zero is considered as False. Consider the following example:

>>> list = [12,9,0]
>>> all(list)
Output : False

The all() method will behave in same way if the list contains a False.

>>> list = [12,4,5,False]
>>> all(list)
False

For an empty iterable the all returns True.

>>> list = []
>>> all(list)
True

In case of dictionaries, if all keys (not values) are true or the dictionary is empty, all() returns True. Else, it returns false for all other cases.

# In the following Dictionary One key is 0, So all will returns False
dictionary_1 = {0: 'False', 1: 'False'}
print(all(dictionary_1))

Following is another dictionary where a key is False, so the all method will returns False.

>>> s = {1: 'True', False: 0}
>>> print(all(s))
False
# For empty dictionary, all() will returns True
>>> s = {}
>>> print(all(s))
True

# 0 is False but '0' is True
>>> s = {'0': 'True'}
>>> print(all(s))
True

How any() works with Python List ?

Returns True if at least one element of an iterable is true. Following are some example:

>>> list = [1, 3, 4, 0]
>>> print(any(list))
True

No elements of an iterable is true

list = [0, False]
print(any(list))
False

0 / False are considered as False, but ‘0’ / ’False’ are not considered as False.

>>> list = ['0','False']
>>> print(any(list))
True

For an empty iterable the any() method returns False.

>>> list = []
>>> print(any(list))
False

In case of dictionaries, if all keys (not values) are false, any() returns False. If at least one key is true, any() returns True.

d = {0: 'False'}
print(any(d))

d = {0: 'False', 1: 'True'}
print(any(d))

d = {0: 'False', False: 0}
print(any(d))

d = {}
print(any(d))

# 0 is False
# '0' is True
d = {'0': 'False'}
print(any(d))

The output of the above programs are :

False
True
False
False
True

Python 12

FOLLOW US ON LinkedIn



Explore Tutu'rself