In the python docs page for any
, the equivalent code for the any()
function is given as:
def any(iterable):
for element in iterable:
if element:
return True
return False
How does this function know what element I wanna test if call it in this form?
any(x > 0 for x in list)
From the function definition, all I can see is that I'm passing an iterable object. How does the for
loop know I am looking for something > 0
?
This question is related to
python
(x > 0 for x in list)
in that function call creates a generator expression eg.
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
Which any
uses, and shortcircuits on encountering the first object that evaluates True
It's because the iterable is
(x > 0 for x in list)
Note that x > 0
returns either True
or False
and thus you have an iterable of booleans.
>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True
>>> all(n in 'King and Queen' for n in names)
False
It just reduce several line of code into one. You don't have to write lengthy code like:
for n in names:
if n in 'King and john':
print True
else:
print False
Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.
list = [2,-3,-4,5,6]
a = any(x>0 for x in lst)
print a:
True
list = [2,3,4,5,6,7]
a = any(x<0 for x in lst)
print a:
False
Source: Stackoverflow.com