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 Answers
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.
Comments
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
None. So I've not seen anything about np.empty being dangerous (intentionally or not).
emptyallocates 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.emptyprobably isn't the best name for the function. Perhapsallocate_uninitializedwould be more descriptive (but a bit long).