user5563109 user5563109 - 1 year ago 216
Python Question

NumPy MemoryError when using array constructors

I'm creating a couple of arrays using numpy and list constructors, and I can't figure out why this is failing. My code is:

import numpy as np
A = np.ndarray( [i for i in range(10)] ) # works fine
B = np.ndarray( [i**2 for i in range(10)] ) # fails, with MemoryError

I've also tried just
B = [i**2 for i in range(10)]
which works, but I need it to be an ndarray. I don't see why the normal constructor would work but calling a function wouldn't. As far as I understand, the ndarray constructor shouldn't even see the inside of that, it should get a length 10 list with ints in it for both.

Answer Source is a low-level method that we normally don't use. Its first argument is the shape.

In [98]: np.ndarray([x for x in range(3)])
Out[98]: array([], shape=(0, 1, 2), dtype=float64)
In [99]: np.ndarray([x**2 for x in range(3)])
Out[99]: array([], shape=(0, 1, 4), dtype=float64)

Normally use zeros or ones to construct a blank array of a given shape:

In [100]: np.zeros([x**2 for x in range(3)])
Out[100]: array([], shape=(0, 1, 4), dtype=float64)

Use np.array if you want to turn a list into an array:

In [101]: np.array([x for x in range(3)])
Out[101]: array([0, 1, 2])
In [102]: np.array([x**2 for x in range(3)])
Out[102]: array([0, 1, 4])

You can generate the range numbers, and then perform the math on the whole array (without iteration):

In [103]: np.arange(3)**2
Out[103]: array([0, 1, 4])