[Numpy-discussion] numpy.array does not take generators

Robert Kern robert.kern at gmail.com
Fri Aug 17 02:19:53 EDT 2007

Geoffrey Zhu wrote:
> Hi All,
> I want to construct a numpy array based on Python objects. In the
> below code, opts is a list of tuples.
> For example,
> opts=[ ('C', 100, 3, 'A'), ('K', 200, 5.4, 'B')]
> If I use a generator like the following:
> K=numpy.array(o[2]/1000.0 for o in opts)
> It does not work.
> I have to use:
> numpy.array([o[2]/1000.0 for o in opts])
> Is this behavior intended?

Yes. With arbitrary generators, there is no good way to do the kind of
mind-reading that numpy.array() usually does with sequences. It would have to
unroll the whole generator anyways. fromiter() works for this, but you are
restricted to 1-D arrays which is a lot easier to implement the mind-reading for.

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