Javaexercise.com

Python any() Method

Python any() method is a built-in method. It is used to check that any element in iterable (list, tuple, set) is True. It returns True, if any element in the iterable is True. It returns False when all the elements are False or the iterable is empty.


Signature

any(iterable)

Parameter Description
iterable (Required) This argument can be a list, tuple, dictionary etc.


Return Value

It returns either True or False based on the elements present in the iterable.


Error: It returns an error (TypeError), if the argument is not an iterable.


Python any() Method Example

Let’s first understand, how this method works and what does it return?

#Creating a list
list1 = [1,0,25,9.5]
#Creating a tuple
tuple1 = ("Javaexercise.com", "is a learning platform",None)
#Creating a dictionary
dict1 = {0: 'zero', 1: 'one'}
#Applying any() method
r1 = any(list1)
r2 = any(tuple1)
r3 = any(dict1)
#Displaying return values
print(r1)
print(r2)
print(r3)
 Output:
 True
 True
 True

Note: In dictionary, only keys are consider. If any single key is True, it returns True.



Python any() Method Example: If iterable is empty or having False values.

#Creating a list
list1 = [0,0.0,False]
#Creating an empty tuple
tuple1 = ()
#Creating a dictionary
dict1 = {0:'zero'}
#Creating an empty string
str1 = ''
#Applying any() method
r1 = any(list1)
r2 = any(tuple1)
r3 = any(dict1)
r4 = any(str1)
#Displaying return value
print(r1)
print(r2)
print(r3)
print(r4)
 Output:
 False
 False
 False
 False