Python any() Function

any() function returns True, if any element of a list (iterable) is True.

mylist = [False,False,True]
result = any(mylist)
print(result) # Output : True
Syntax

any(iter)

Parameters

any() takes a single parameter; iter i.e. an iterable. The iterable can be list, tuple, dictionary, etc.

Return Value
  • True If at least one element in the iterable is true.
  • False – If all the elements are false (or the iterable is empty).
Examples

Working of any() with lists

# all elements are True
l1 = [1,2,3,4]
print('l1 : ',any(l1))

# all elements are False
l2 = [False,0]
print('l2 : ',any(l2))

# one element is True
l3 = [0,1,0]
print('l3 : ',any(l3))

# empty
l4 = []
print('l4 : ',any(l4))

Output

l1 :  True
l2 :  False
l3 :  True
l4 :  False

Working of any() with tuple and set

t = (0,False,1)
print('t : ',any(t))

s = {False,0}
print('s : ',any(s))

Output

t :  True
s :  False

Check if all the elements in a dictionary are True.

When the any() function is used on a dictionary, it checks the keys, not the values, i.e. if any key is True it returns True.

d1 = {1 : 'iPhone', 2 : 'Samsung'}
print('d1 :',any(d1))

d2 = {0 : False, 1 : True}
print('d2 :',any(d2))

d3 = {}
print('d3 :',any(d3))

Output

d1 : True
d2 : True
d3 : False

Note:

  • any() can be used on a string. Only if the string is empty then any() returns False, and True in any other case.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.