Python all() Function

all() function returns True, if all the elements of a list (iterable) are True.

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

all(iter)

Parameters

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

Return Value
  • True If all the elements in an iterable are true or the iterable is empty.
  • False – If atleast one element is false.
Examples

Check if all the elements in a list are True.

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

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

# one element is False (0 indicates False)
l3 = [1,2,0]
print('l3 : ',all(l3))

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

Output

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

Check if all the elements in a tuple or in a set are True.

t = (True,False,1)
print('t : ',all(t))

s = {10,20}
print('s : ',all(s))

Output

t :  False
s :  True

Check if all the elements in a dictionary are True.

When the all() function is used on a dictionary, it checks the keys, not the values, i.e. if all the keys are True or the dictionary is empty, then all() returns True.

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

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

d3 = {False : 'Incorrect', True: 'Correct'}
print('d3 :',all(d3))

Output

d1 : True
d2 : False
d3 : False

Note:

  • all() can be used on a string and it will return True for string data.

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.