Javaexercise.com

Python all() Method

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

True means: any iterable that does not contain any element like: 0(zero), 0.0, false, None, will be treated as True.


Signature

all(iterable)

Parameter Description
iterable (Required) This argument can be a list, tuple, dictionary, string 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 all() Method Example

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

#Creating a list
list1 = [1,3,5,7,9.5]
#Creating a tuple
tuple1 = ("Javaexercise.com", "is a learning platform")
#Creating a dictionary
dict1 = {1: 'One', 2: 'Two'}
#Applying all() method
r1 = all(list1)
r2 = all(tuple1)
r3 = all(dict1)
#Displaying return values
print(r1)
print(r2)
print(r3)
 Output:
 True
 True
 True

Note: In dictionary, only keys are consider. if all the keys are True, it returns True.



Python all() Method Example

This method returns false in the following scenarios.

#Creating a list
list1 = [1,3,0,7,9.5]
#Creating a tuple
tuple1 = ("technical99", "a learning platform",None)
#Creating dictionary with a False value
dict1 = {0: 'Zero', 1: 'One'}
#all() method
r1 = all(list1)
r2 = all(tuple1)
r3 = all(dict1)
#Displaying return value
print(r1)
print(r2)
print(r3)
 Output:
 False
 False
 False

Python all() Method Example: If iterable is empty

#Creating an empty list
list1 = []
#Creating an empty tuple
tuple1 = ()
# Creating an empty dictionary
dict1 = {}
#Creating an empty string
str1 = ''
#Applying all() method
r1 = all(list1)
r2 = all(tuple1)
r3 = all(dict1)
r4 = all(str1)
#Displaying return value
print(r1)
print(r2)
print(r3)
print(r4)
 Output:
 True
 True
 True
 True