Skip to content

Python any() Function

How to use Python's any() function to check if at least one element in an iterable (list, tuple, dictionary, etc.) evaluates to True, including handling empty iterables and falsy values.

The any() function returns True if any item in an iterable is True. Otherwise, it returns False.

Syntax

any(iterable)

any() Parameters

Python any() function parameters:

Parameter Condition Description
iterable Required An iterable of type (list, string, tuple, set, dictionary etc.)

any() Return Value

Python any() function returns a boolean value:

  • True if at least one element of an iterable is true
  • False if all elements are false or if an iterable is empty

Falsy Values in Python

Falsy values are those that evaluate to False in a boolean context:

  • Constants defined to be false: None and False.
  • Zero of any numeric type: Integer (0), Float (0.0), Complex (0j), Decimal(0), Fraction(0, 1).
  • Empty sequences and collections: Lists ([]), Tuples (()), Dictionaries ({}), Sets (set()), Strings (""), range(0)
  • Any custom object for which the __bool__() method is defined to return False, or the __len__() method returns 0 when __bool__() is not defined.

Examples

Some examples of how to use any() function.

any() function on List

my_list = [0, 0, 0]
print(any(my_list))   # Output: False

my_list = [0, 1, 1]
print(any(my_list))   # Output: True

output

False
True

Other examples:

my_list = [False, 0, 1]
print(any(my_list))   # Output True

my_list = ('', [], 'green')
print(any(my_list))   # Output True

my_list = {0j, 3+4j, 0.0}
print(any(my_list))   # Output True

output

True
True
True

any() function on a Dictionary

The function any() can be used on dictionaries.

When you use any() function on a dictionary, it checks if any the keys of the dictionary are true (and not the values).

dict1 = {0: 'Zero', 0: 'Nil'}
print(any(dict1))   # Output: False

dict2 = {'Zero': 0, 'Nil': 0}
print(any(dict2))   # Output: True

output

False
True

any() function on Empty Iterable

The function any() can be used on iterables. In particular, if the iterable is empty, the function returns False.

my_list = []
print(any(my_list))   # Output: False

my_list = [[], []]
print(any(my_list))   # Output: False

output

False
False
Navigation