5

Is there a way to do a numpy array comprehension in Python? The only way I have seen it does is by using list comprehension and then casting the results as a numpy array, e.g. np.array(list comprehension). I would have expected there to be a way to do it directly using numpy arrays, without using lists as an intermediate step.

Also, is it possible to overload list operators, i.e. [ and ], so that the results is a numpy array, not a list.

Confounded
  • 446
  • 6
  • 19
  • 3
    "is it possible to overload list operators, i.e. [ and ], so that the results is a numpy array, not a list."-- sounds like a really bad idea – Chris_Rands Dec 10 '19 at 10:33
  • Not sure what "array comprehension" would even entail. What functionality do you want from it? – Daniel F Dec 10 '19 at 10:36
  • 1
    Python lists are part of the Python language definition, Numpy arrays aren't; they're part of a third party library that the Python language has no knowledge of (alas Python was never originally *designed* with scientific computation in mind, even though it has become popular and useful for that in some domains). – Iguananaut Dec 10 '19 at 10:45
  • The question is: why would you like to do it? – mrzo Dec 10 '19 at 10:54

2 Answers2

7

You can create the numpy array from a generator expression. You just have to specify the dtype in advance:

import numpy as np
x = np.fromiter(range(5), dtype=int)
y = np.fromiter((i**2 for i in range(5)), dtype=int)
user2653663
  • 2,818
  • 1
  • 18
  • 22
0

A fundamental problem here is that numpy arrays are of static size whereas python lists are dynamic. Since the list comprehension doesn't know a priori how long the returned list is going to be, one necessarily needs to maintain a dynamic list throughout the generation process.

Hyperplane
  • 1,422
  • 1
  • 14
  • 28