np.empty() function in NumPy is used for creating an array without initializing its entries. This function is particularly useful when you need an array of a specific shape and datatype, but the initial values are not important and will be overwritten during subsequent operations. It is a way to optimize performance by avoiding the overhead of initializing the array values.
Example of Creating an Uninitialized Array using np.empty()
Here’s how you can use
np.empty() to create an uninitialized array of shape (3, 4):
import numpy as np # Create an uninitialized array of shape (3, 4) arr = np.empty((3, 4)) print(arr)
The output of this code will be an array of shape (3, 4), but the contents of the array are unpredictable as they are whatever happens to be in the allocated memory at the time. Here’s an example output:
[[4.68858538e-310 0.00000000e+000 6.94916243e-310 6.94915286e-310] [6.94915326e-310 6.94916243e-310 6.94915286e-310 6.94915286e-310] [6.94915286e-310 6.94915286e-310 6.94916243e-310 6.94915243e-310]]
Important Notes about np.empty()
- Uninitialized Data: The
np.empty()function does not set the array values to zero or any other value. It merely allocates memory, and the array contains whatever data happens to already be in that memory location. This can lead to confusion if you’re expecting a clear, zeroed, or default-initialized array.
- Performance Consideration: Since
np.empty()skips the initialization step, it can be slightly faster than functions like
np.oneswhich explicitly set each array value. This can be an advantage in scenarios where performance is critical and you know the array will be filled with data before any computation that reads its values.
- Array Contents: The contents of an uninitialized array can be any value, including very large numbers, very small numbers, or even values that make no sense in your context. They often appear as very small numbers close to zero, but this is not guaranteed.
Creating empty NumPy Array of Specific Datatype
You can also specify the desired datatype for the elements of the array:
import numpy as np # Create an uninitialized array of # integers of shape (2, 3) arr = np.empty((2, 3), dtype=int) print(arr)
Output may vary as the array is uninitialized:
[[23127395242 7 9] [ 0 5 0]]
In this example, the array is intended to hold integers. The actual values are unpredictable and depend on the state of the memory.
The primary use case for
np.empty() is in scenarios where you need a container for data and are certain that every element will be explicitly set before any computations are performed on the array. This is common in algorithms where the array serves as a buffer or a temporary storage, and its initial state is irrelevant.