Python built-in module provides method any() which returns True if any element of an iterable is true. If not this method would return False.
syntax :
any(iterable) ## iterable could be list, string dict etc
return value:
syntax :
any(iterable) ## iterable could be list, string dict etc
return value:
- True ## if any 1 of iterable is True
- False ## if all are false or the list is empty
>>> a = [0,0] ## 0 defaults to False >>> any(a) False >>> a = [1,2] ## Both are True >>> any(a) True >>> a = [] ## empty list False >>> any(a) False >>> a = [0,0,0,1] ## If any element is True >>> any(a) True
Using any() with 2 lists :
Suppose We have two lists a and b and we want to check if element in a exists in b.
So we define function :
def func(a, b):
for i in a:
if i in b:
return True
return False
This could be easily realised with any() in one line as :
any(i in b for i in a)
For Example:
>>> a = [1,2,3,4] >>> b = [4,5,6,7] False >>> def func(a, b): for i in a: if i in b: return True return False >>> print func(a,b) True >>> any(i in b for i in a) True
No comments:
Post a Comment