[Numpy-discussion] bad generator behaviour with sum
Robert Kern
robert.kern at gmail.com
Sun Aug 27 17:41:36 CDT 2006
listservs at mac.com wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Aug 27, 2006, at 4:19 PM, numpy-discussion-
> request at lists.sourceforge.net wrote:
>
>>> It seems like numpy.sum breaks generator expressions:
>>>
>>> In [1]: sum(i*i for i in range(10))
>>> Out[1]: 285
>>>
>>> In [2]: from numpy import sum
>>>
>>> In [3]: sum(i*i for i in range(10))
>>> Out[3]: <generator object at 0x10eca58>
>>>
>>> Is this intentional? If so, how do I get the behaviour that I am
>>> after?
>>>
>>
>> In [3]: sum([i*i for i in range(10)])
>> Out[3]: 285
>
> Well, thats a list comprehension, not a generator expression. I was
> after the latter because it is more efficient.
Not really. Any numpy functions that would automatically create an array from an
__len__-less iterator will have to convert it to a list first. That said, some
cases for numpy.sum() might be handled by passing the argument to
__builtin__.sum(), but it might be tricky devising a robust rule for when that
happens. Consequently, I would like to avoid doing so.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion
mailing list