In this tutorial we will discuss about the any() function in python programming language with the examples.
Python any() function
The built-in function uses the iterables to return the value or . The iterables can be dictionary, tuple, List, strings etc. It returns True if any element of the given iterable is true and False if all the elements of iterable are false or the iterable is empty.
Syntax of Python any() function:
any(iterable)
Parameter of any() function in python
The python built-in function also takes only one argument i.e. iterables. Iterable can be any object like list, dictionary, tuple, etc. which includes all the elements.
Return value of Python any() function
The python function returns the value as follows;
True - It returns True if any element of the given iterable is true.
False - It returns False if all the elements of iterable are false or the iterable is empty.
Example 1: How Python any() works for Lists?
# All elements of list are trueli = [ 14, 9, 11]
print(any(li))
# All elements of list are false
li = [ False, 0, 0]
print(any(li))
# three elements of list are true while others are false
li = [ 1, 0, 19, False, 7]
print(any(li))
# Empty List
li = []
print(any(li))
Output
TrueFalse
True
False
Example 2: How Python any() works for Tuples?
# all elements are truetup = (14, "Answersjet", 2)
print(any(tup))
# all elements are false
tup = (False, 0, 0)
print(any(tup))
# one element is true rest are false
tup = (14, False, 0)
print(any(tup))
# one element is false rest are true
tup = (False, 14, 29, 34)
print(any(tup))
# empty tuple
tup = ()
print(any(tup))
Output
TrueFalse
True
True
False
Example 3: How Python any() works for Strings?
# All elements of the string are truestr = "I love Python", "Answersjet"
print(any(str))
# 0 is False but '0' is True because it is a string character
str = '000'
print(any(str))
# empty string
str = ''
print(any(str))
Output
TrueTrue
False
Example 4: How Python any() works for Dictionary?
# all keys are truedic = {1: 'False', 2: 'True'}
print(any(dic))
# one key is false rest is true
dic = {0: 'False', 14: 0}
print(any(dic))
# One key is true, '0' is True because it is a string not a number
dic = {'0': 'False'}
print(any(dic))
# empty dictionary
dic = {}
print(any(dic))
Output
TrueTrue
True
False