7

What is the reason for this weirdness in numpy's all?

>>> import numpy as np
>>> np.all(xrange(10))
False
>>> np.all(i for i in xrange(10))
True
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
wim
  • 338,267
  • 99
  • 616
  • 750
  • `np.__version__` is 1.6.2 – wim Jan 18 '13 at 02:35
  • 3
    You can read [this thread](https://groups.google.com/forum/?fromgroups=#!topic/numpy/RRvH2NgR3Ik) for some of the back-and-forth. I come down on the throw-an-exception side. – DSM Jan 18 '13 at 02:38
  • related: http://www.mail-archive.com/numpy-discussion@scipy.org/msg06476.html – wim Jan 18 '13 at 05:09

2 Answers2

7

Numpy.all does not understands generator expressions.

From the documentation

 numpy.all(a, axis=None, out=None)

    Test whether all array elements along a given axis evaluate to True.
    Parameters :    

    a : array_like

        Input array or object that can be converted to an array.

Ok, not very explicit, so lets look at the code

def all(a,axis=None, out=None):
    try:
        all = a.all
    except AttributeError:
        return _wrapit(a, 'all', axis, out)
    return all(axis, out)

def _wrapit(obj, method, *args, **kwds):
    try:
        wrap = obj.__array_wrap__
    except AttributeError:
        wrap = None
    result = getattr(asarray(obj),method)(*args, **kwds)
    if wrap:
        if not isinstance(result, mu.ndarray):
            result = asarray(result)
        result = wrap(result)
    return result

As generator expression doesn't have all method, it ends up calling _wrapit In _wrapit, it first checks for __array_wrap__ method which generates AttributeError finally ending up calling asarray on the generator expression

From the documentation of numpy.asarray

 numpy.asarray(a, dtype=None, order=None)

    Convert the input to an array.
    Parameters :    

    a : array_like

        Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

It is well documented about the various types of Input data thats accepted which is definitely not generator expression

Finally, trying

>>> np.asarray(0 for i in range(10))
array(<generator object <genexpr> at 0x42740828>, dtype=object)
Abhijit
  • 62,056
  • 18
  • 131
  • 204
0

Strange. When I try that I get:

>>> np.all(i for i in xrange(10))
<generator object <genexpr> at 0x7f6e04c64500>

Hmm.

I don't think numpy understands generator expressions. Try using a list comprehension and you get this:

>>> np.all([i for i in xrange(10)])
False
Community
  • 1
  • 1
Eevee
  • 47,412
  • 11
  • 95
  • 127