The built-in function all()
is supposed to be equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
But when a generator expression is passed to all()
, the behaviors are different:
l=(1,2,3)
def all2(iterable):
for element in iterable:
if not element:
return False
return True
print all(e > 0 for e in l) # <generator object <genexpr> at 0x00000000096AB510>
print all2(e > 0 for e in l) # True
Same goes for the other similar built-ins. Is there a simple way to fix it? (Converting the generator expression to a tuple or a list is not really an option, because of the footprint.)
numpy
has its own all
function that behaves differently from the built-in all
:
>>> numpy.all(x for x in range(3))
<generator object <genexpr> at 0x0000000001FD2900>
>>> all(x for x in range(3))
False
If for some reason all
refers to numpy.all
instead of __builtin__.all
, perhaps due to a from numpy import *
or due to automatic imports performed by the Python distribution you're using, you will get the NumPy behavior instead of what the built-in does.