12

are there any way to create an object form any class inside a numpy array?. Something like:

a = zeros(4)

for i in range(4):
   a[i]=Register()

Thanks

2 Answers 2

19

Yes, you can do this:

a = numpy.array([Register() for _ in range(4)])

Here, a.dtype is dtype('object').

Alternatively, if you really need to reserve memory for your array and then build it element by element, you can do:

a = numpy.empty(shape=(4,), dtype=object)
a[0] = Register()  # etc.
Sign up to request clarification or add additional context in comments.

1 Comment

@Mike: thank you for spotting the typo in the first solution; what I meant was of course what you put in your solution. I had forgotten to build the list first; it's now corrected. For the second solution, I switched to numpy.empty.
5

The items in numpy arrays are statically typed, and when you call zeros you make an array of floats. To store arbitrary Python objects, use code like

numpy.array([Register() for i in range(4)])

which makes an array with dtype=object, which you could also specify manually.

Consider whether you really want numpy in this case. I don't know how close this example is to your use case, but oftentimes a numpy array of dtype object, especially a one-dimensional one, would work at least as well as a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.