Python any() Function

Python any() function returns True if at least one element of an iterable is Truthy. If no element in iterable is True, any() returns False.

any() can be thought of as logical OR operation on elements on iterable.

  • All values are True, any() returns True.
  • All values are False, any() returns False.
  • One value is True (others are False), any() returns True.
  • One value is False (others are True), any() returns True.
  • Empty Iterable, any() returns False.

Syntax

The syntax of any() method is :

return_val = any( iterable )

Function parameter and return value

  • The any() method takes a single required argument of iterable type, for example a list, set, tuple or dictionary.
  • The return value is of bool type whose value is either True or False.

Python any() Function Example

any() Function with Tuple

Python program to check if any item in a tuple is True. In given tuple, the value 1 is considered as True.

mytuple = (0, 1, False)
bool_result = any(mytuple)

print('Return value is: ', bool_result)

Program output.

Return value is:  True

any() Function with List

Python program to check if any item in a list is True. In the given list, all elements are False.

myList = [0, False]
bool_result = any(myList)

print('Return value is: ', bool_result)

Program output.

Return value is:  False

any() Function with Dictionary

Python program to check if any item in a dictionary is True. In the given dictionary, the first instance is having a single False value. The second instance has two values, first is False, and second is True.

d = {0: 'False'}
bool_result = any(d)
print('Return value is: ', bool_result)

d = {0: 'False', 1: 'True'}
bool_result = any(d)
print('Return value is: ', bool_result)

Program output.

Return value is:  False
Return value is:  True

any() Function with String

Python program to use any() to check is string is empty or not. For an empty string, any() wil retur False, else it will return True.

s = ''
bool_result = any(s)
print('Return value is: ', bool_result)

s = '  '
bool_result = any(s)
print('Return value is: ', bool_result)

s = 'abc'
bool_result = any(s)
print('Return value is: ', bool_result)

s = '123'
bool_result = any(s)
print('Return value is: ', bool_result)

Program output.

Return value is:  False
Return value is:  True
Return value is:  True
Return value is:  True

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.