Python Built-in Function all():

The all() method returns true if all the elements in iterable(List, Dictionary, Tuple, Set) are true or non zero. However, if one of the values is zero or false, this method returns false. It also returns true if an iterable object is empty.

Signature

The signature for the all() method is as shown below. Here, iterable can be a list, dictionary, tuple, or set. The variable r stores the boolean value returned from the method.

r=all(iterable)

Parameters and return type

  • Here, The all() method takes an iterable object as a parameter.
  • However, it returns the boolean value True or False.

Python Built-in Function all Examples:

Example 1: In this example, let us take a list l and set s containing some numbers. At this time, the list contains value 0 so, the all() will return False. But the set contains all non zero values. Hence it returns value True.

#Initializing 
l=[0,1,2,3,4]
s={1,2,3,4,5}
# Using all method and printing
r=all(l)
print("List contains all non zero values - ",r)
r=all(s)
print("Set contains all non zero values - ",r)

Output

List contains all non zero values - False
Set contains all non zero values - True

Example 2: In this case, We will take a dictionary with key-value pair to demonstrate the working of all() method. As we can see, this method returns false if one of the keys has a value zero. However, it returns true even if all the value fields have zero.

#Initializing 
d1={0:"Zero",2:"Two",3:"Three"}
d2={1:0,2:0,3:0}
#Using all method and printing
r=all(d1)
print("Dictionary d1 contains all non zero elements",r)
r=all(d2)
print("Dictionary d2 contains all non zero elements",r)

Output

Dictionary d1 contains all non zero elements False
Dictionary d2 contains all non zero elements True

Example 3: In this example, We will print the elements of two sets if all the values in the set are non zero; otherwise, we will print an error message.

#Initializing 
s1={10,20,30,40,50}
s2={55,32,66,0,90}
#Using all method and printing
if all(s1):
	print("Set s1 = ",s1)
else:
	print("Set s1 has some zero value elements")
if all(s2):
	print("Set s2 = ",s2)
else:
	print("Set s2 has some zero value elements")	

Output

Set s1 =  {40, 10, 50, 20, 30}
Set s2 has some zero value elements

Conclusion

The all() method returns a true value if the iterable contains all non zero values. However, it returns false otherwise.

References

Happy Learning 🙂

Leave A Comment