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.

4
  • 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 Commented Dec 10, 2019 at 10:33
  • Not sure what "array comprehension" would even entail. What functionality do you want from it? Commented Dec 10, 2019 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). Commented Dec 10, 2019 at 10:45
  • The question is: why would you like to do it? Commented Dec 10, 2019 at 10:54

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.