Python any() function accepts iterable (list, tuple, dictionary etc.) as an argument and return true if any of the element in iterable is true, else it returns false. If iterable is empty then any() method returns false.
Python any() function example with lists
The any() function returns true if any of the element in the passed list is true. Here we are taking various lists with different items to demonstrate the output of any() function in different situations.
# all values are true lis1 = [10, 20, 30, 40] print(any(lis1)) # all values are false lis2 = [0, False] print(any(lis2)) # one value is false, others are true lis3 = [0, 10, 5, 15] print(any(lis3)) # one value is true, others are false lis4 = [10, 0, False] print(any(lis4)) # empty iterable lis5 = [] print(any(lis5))
Output:
Python any() function example with Dictionaries
The any() function only checks the keys (not values) in the passed dictionary. If any of the key is true in the dictionary then any() function returns true, else it returns false. The any() function returns false for empty dictionary as well.
# all keys are true dict1 = {1: 'False', 2: 'True'} print(any(dict1)) # all keys are false dict2 = {0: 'False', False: 'True'} print(any(dict2)) # one key is false, other is true dict3 = {0: 'False', 1: 0} print(any(dict3)) # One key is true, '0' is not false its True # because '0' is a string not a number # if it is 0 without quotes then its false dict4 = {'0': 'False'} print(any(dict4)) # empty dictionary dict5 = {} print(any(dict5))
Output:
Python any() function example with Tuples
Python any() function returns true if any of the item in tuple is true else it returns false. The any function returns false if the passed tuple is empty.
# all elements are true t1 = (1, "BeginnersBook", 22) print(any(t1)) # all elements are false t2 = (0, False, 0) print(any(t2)) # one element is true others are false t3 = (1, 0, False) print(any(t3)) # one element is false others are true t4 = (False, 1, 2, 3) print(any(t4)) # empty tuple t5 = () print(any(t5))
Output:
uswah says
how to use “any” function in finding either it is the member of list or not
crabbycoder says
cant we use “in ” or ” not in ” for that instead
LA says
This was helpful, thank you for this tuturial.