Pages

11 April, 2022

Python all() Function

Python all() Function

The python all() function accepts an iterable object (such as list,dictionary etc.). It returns True if all items in passed iterable are true, otherwise it returns False. If the iterable object is empty, the all() function returns True.

Signature

  1. all (iterable)  

Parameters

  • iterable - The objects which contain the elements i.e. list, tuple and dictionary, etc.

Return

  • True - If all the elements in an iterable are true.
  • False - If all the elements in an iterable are false..

Python all() Function Example 1

Let's see how all() works for lists?

  1. # all values true  
  2. k = [1345]  
  3. print(all(k))  
  4.   
  5. # all values false  
  6. k = [0False]  
  7. print(all(k))  
  8.   
  9. # one false value  
  10. k = [1340]  
  11. print(all(k))  
  12.   
  13. # one true value  
  14. k = [0False5]  
  15. print(all(k))  
  16.   
  17. # empty iterable  
  18. k = []  
  19. print(all(k))  

Output:

True
False
False
False
True

Python all() Function Example 2

The below example shows how all() works for dictionaries.

  1. # Both the keys are true  
  2. dict1 = {1'True'2'False'}  
  3. print(all(dict1))  
  4.   
  5. # One of the key is false  
  6. dict2 = {0'True'1'True'}  
  7. print(all(dict2))  
  8.   
  9. # Both the keys are false  
  10. dict3 = {0'True'False0}  
  11. print(all(dict3))  
  12.   
  13. # Empty dictionary  
  14. dict4 = {}  
  15. print(all(dict4))  
  16.   
  17. # Here the key is actually true because  
  18. #  0 is non-null string rather than a zero  
  19. dict5 = {'0''True'}  
  20. print(all(dict5))  

Output:

True
False 
False 
True 
True

Python all() Function Example 3

The below example shows how all() works for tuples.

  1. # all true values  
  2. t1 = (12345)  
  3. print(all(t1))  
  4.   
  5. # one false value  
  6. t2 = (01"Hello")  
  7. print(all(t2))  
  8.   
  9. # all false values  
  10. t3 = (0False , 0)  
  11. print(all(t3))  
  12.   
  13. # one true value, all false  
  14. t4 = (True0False)  
  15. print(all(t4))  

Output:

True 
False 
False 
False

No comments:

Post a Comment

Thanks