The all() built-in function of Python

Function signature:

all(iterable)

Parameters:

iterable - A Python iterable. The containers list, tuple, setdictionary and any object that support the iterable protocol of Python are collectively called iterables.

Return value:

Returns a Boolean value.

True when each of the elements in the iterable evaluates True or when len(iterable) is zero. Returns False otherwise.

Overview:

  • The all() function checks whether a Python iterable object has all of its elements evaluate to True. For example, a Python list object with some of its elements as None makes the all() method return False.
  • If the iterable object is empty, the all() function returns True.
  • This behaviour is the opposite of any() function where any() will return True if any of the elements of an iterable evaluate to True.

Example:

# Example Python program that checks few iterables - a list 
# with numbers and None, an empty list and a tuple - whether
# all of their elements evaluate to True using the Python built-in 
# function all().

# List with numbers and None
mixedList = [5, 7, 3, None, 15, 12, 11, None]
result      = all(mixedList)
print(result)

# An empty list
emptyList = []
result  = all(emptyList)
print(result)

# A tuple
rgb = (115, 120, 125) 
result  = all(rgb)
print(result)

Output:

False

True

True

 


Copyright 2024 © pythontic.com