6

https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.empty.html

reads that "Return a new array of given shape and type, without initializing entries." Q1:what do "without initializing entries." mean here. Q2:Are the output returned by np.empty() are random numbers? I am using below code to generate an array and I am getting same output so how could they be random numbers?

import numpy as np

print(np.empty([2,2]))

1

1 Answer 1

9

The array is allocated in memory but each item in the area is uninitialized just like an uninitialized variable. In other words, the items in the array have not had their values set and are just taking the value that was held in memory until you explicitly assign them a value. Sometimes this value is 0 or close to it, but there is no guarantee what was in memory at those locations. Here is the note on the reference page:

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

So unless you have a certain use case, go with zeros or something else. I'll also note that typically Python does not allow you to just declare a variable without initializing it, which is why this behavior might seem strange.

1
  • I juste came across a case where np.empty returned 1000 which was confusing since I did not understood if this quite common value came from the code I work with. Commented Aug 8 at 13:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.