Python all() function accepts an iterable object (such as list, dictionary etc.) as an argument. If all the elements in the passed iterable are true then all() function returns true else it returns false. If the iterable is empty then also this function returns true.
Python all() function works on?
The all() function can be used on any iterable such as lists, tuples, dictionaries etc.
Python all() function example with lists
In this example, we will see how the all() function works with the lists. We have taken several lists with different values to demonstrate the output of all() function in different scenarios. The 0 (zero) values in lists are considered as false and the non-zero values such as 1, 20 etc are considered true.
# all values of this list are true # non-zero values are considered true lis1 = [10, 5, 15, 77] print(all(lis1)) # all values are false # 0 is considered as false lis2 = [0, False, 0] print(all(lis2)) # one value is false, others are true lis3 = [10, 0, 40] print(all(lis3)) # one value is true, others are false lis4 = [0, 0, True] print(all(lis4)) # empty iterable - no elements lis5 = [] print(all(lis5))
Output:
Python all() function example with Dictionary
# Both the keys are true dict1 = {1: 'True', 2: 'False'} print(all(dict1)) # One of the key is false dict2 = {0: 'True', 1: 'True'} print(all(dict2)) # Both the keys are false dict3 = {0: 'True', False: 0} print(all(dict3)) # Empty dictionary dict4 = {} print(all(dict4)) # Note: Here the key is actually true because # '0' is a non-null string rather than a zero dict5 = {'0': 'True'} print(all(dict5))
Output:
Python all() function example with Strings
# non-null string s1 = "Hello World" print(all(s1)) # non-null String s2 = '0' print(all(s2)) # non-null String s3 = '' print(all(s3)) # non-null String s4 = 'False' print(all(s4))
Output:
True True True True
Python all() example with tuples
# all true values t1 = (1, 2, 3, 4, 5) print(all(t1)) # one false value t2 = (0, 1, "Hello") print(all(t2)) # all false values t3 = (0, False , 0) print(all(t3)) # one true value, all false t4 = (True, 0, False) print(all(t4))
Output:
Leave a Reply