Python any() Function with Examples

How to Use the Python any() Function

In this tutorial, you will learn how to use the Python any() function, which returns True if any of the given iterable elements, such as a list, tuple, or dictionary, is True. Otherwise, it returns False. If the iterable is empty, any() returns False.

Python any() Syntax

The syntax of the any() function is as follows:

any(iterable)

The any() function Parameter

  • Iterable: Required. It can be a list, tuple, set, dictionary, etc.

Examples

Check if any item in the list is True:

Example 1:

  1. list = ["Apple", "Orange", "Kiwi", 120, 430]
  2. check = any(list)
  3. print(check)

Output:

True

Example 2:

  1. list = [1>2, False, 2==2, 3<2, False]
  2. check = any(list)
  3. print(check)

Output:

True

Check whether any of the items in the tuple are True:

The following code returns True if any item in the tuple is True:

  1. tuple = (1>2, 2>3, 30>30.5, False)
  2. check = any(tuple)
  3. print(check)

Output:

False

Check if any item in the set is True:

The following code returns True if any item in the set is True:

  1. set = {False, 100 > 200, "B"=="B", 240 > 241}
  2. check = any(set)
  3. print(check)

Output:

True

Check if any of the entries in the dictionary are True.

The following code returns True if any of the dictionary entries are True:

  1. dict = {
  2. False: "This key of the dictionary is False!",
  3. 1>2: "This key of the dictionary is False!",
  4. 2>1: "This key of the dictionary is True!"
  5. }
  6. check = any(dict)
  7. print(check)

Output:

True

Note that the any() function checks whether any of the keys in the dictionary is True, not the value.

Check if any item in the empty list is True:

  1. list = []
  2. check = any(list)
  3. print(check)

Output:

False

Summary

In this tutorial, you learned how to use Python's any() function, which returns True if any of the given iterable elements, such as a list, tuple, or dictionary, is True. Otherwise, it returns False. If the iterable is empty, any() returns False.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment