2

I'm just trying to get my head around np.empty(), I understand that it creates an uninitialized array but I'm failing to understand what that means and where the values come from. Any help would be welcomed, thanks in advance.

2
  • 2
    empty allocates memory from the OS, but doesn't write any data to the memory that was allocated, so it will contain whatever happened to be in the memory that was allocated the OS. Commented Jan 31, 2022 at 13:55
  • If we're semantically pedantic, empty probably isn't the best name for the function. Perhaps allocate_uninitialized would be more descriptive (but a bit long). Commented Jan 31, 2022 at 13:57

2 Answers 2

5

numpy.empty functions exactly like numpy.zeros, but it does not care to set values, just sets up the container by allocating the memory to store future elements.

Thus, the values you see are random values deriving from whatever might have been in memory before.

This is why the documentation stresses out that you should only use numpy.empty if you plan to fill the array completely by yourself.

Notes

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.

Sign up to request clarification or add additional context in comments.

Comments

1

numpy is not Python but a wrapper around C code. numpy.empty returns a (wrapper around) an uninitialized C array. You should never try to read a value that you have not previously written because it can be anything including a trap value on systems that have it. It is know as Undefined Behaviour (a close parent to Hell) by C programmers...

2 Comments

Though if the dtype is object, it is filled with None. So I've not seen anything about np.empty being dangerous (intentionally or not).
@hpaulj: I must admit that I have not worked for ages on a system having trap representation for numeric values... But I would not dare to use an uninitialized integer as the dimension of a numpy array! And doc is explicit that the array is only initialized to None for object dtype, which is not the most common type when using numpy.

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.