NumPy MemoryError when using array constructors
<p>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:</p>

<pre><code>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
</code></pre>

<p>I've also tried just <code>B = [i**2 for i in range(10)]</code> 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.</p>

<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html</a> is a low-level method that we normally don't use.  Its first argument is the <code>shape</code>.</p>

<pre><code>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)
</code></pre>

<p>Normally use <code>zeros</code> or <code>ones</code> to construct a blank array of a given shape:</p>

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

<p>Use <code>np.array</code> if you want to turn a list into an array:</p>

<pre><code>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])
</code></pre>

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

<pre><code>In [103]: np.arange(3)**2
Out[103]: array([0, 1, 4])
</code></pre>

python arrays list numpy constructor