Any() and All() function in Python
Python provides two inbuilt functions for "AND" and "OR" 'operations as "All" and "Any" functions.
Any() function
The any() function returns true value if any of the item is true otherwise it will return false if empty or all items are false.
It stops the iteration or we can say it short circuit the execution if the result is known.
Syntax: any (list of iterables)
check all item in tuple
my_list=[False,False,False,False]
mylst=[False,True,False,True]
x=any(my_list)
y=any(mylst)
print(x)
print(y)
Output :
False
True
Lets see an another example related to this function()
check all item in list
print (any([False, False, False, False]))
print (any([False, True, False, False]))
print (any([True, False, False, False]))
Output :
False
True
True
All() function
The all() function will returns True if all items in an iterable are true or if the iterable is empty,
It also short circuit the execution i.e. stop the execution further as soon as the result is known.
lets see an example with list, The iterable object can be list, tuple or dictionary.
mylst = [True, True, False]
my_list = [True,True,True]
x = all(mylst)
y = all(my_list)
print(x)
print(y)
Output :
False
True
lets see an another example
print (all([True, True, True, True]))
print (all([False, True, True, False]))
print (all([False, False, False]))
Output :
True
False
False
An example with Dictionary
mydict = {0: "Apple", 1:"Banana"}
x = all(mydict)
print(x)
Output :
False
Now Lets see some practical examples
list1 = []
list2 = []
for i in range(1,11):
list1.append(4*i)
for i in range(0,10):
list2.append(list1[i]%5==0)
print("lets See whether at least the one number is divisible by 5 in the list 1=>")
print(any(list2))
Output :
lets See whether at least the one number is divisible by 5 in the list 1=>
True
In this article i have discussed about the Any() and All() function
Next article : Inplace and Standard operator in python
Recommended Post : Variable, Expression, Condition and Functions
#any in python
#all in python
#python all
#python any
#python global
#python global variable#python programming
#python list
#learn python
#python requests
#introduction to data science in python
#free python tutorial
#learn python basics
#learn python
#python requests
#introduction to data science in python
#free python tutorial
#learn python basics
1 Comments
Informative and nicely written.
ReplyDeleteIf you have any doubt, Please let me know.