user5563109 - 10 months ago 75

Python Question

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)]`

Answer

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html 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])
```

Source (Stackoverflow)