np.zeros vs np.empty in NumPy
Understanding array initialization, performance, and use cases
NumPy provides multiple ways to create arrays.
Two commonly used functions are np.zeros and np.empty.
While they may look similar, they behave very differently under the hood.
np.zeros
๐ข Purpose & Behavior
np.zeros creates an array of a specified shape and
initializes every element to 0.
This provides a clean and predictable starting point for computations.
๐งช Example
import numpy as np array = np.zeros((3, 3)) print(array)
Output:
[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
Here, a 3×3 array is created and every element is explicitly set to zero.
np.empty
⚠️ Purpose & Behavior
np.empty creates an array of a specified shape
without initializing its values.
The array contains whatever data already exists in memory at the time of allocation—often referred to as “garbage values.”
๐งช Example
import numpy as np array = np.empty((3, 3)) print(array)
Output (example):
[[6.94843117e-310 6.94843117e-310 0.00000000e+000] [0.00000000e+000 6.94843113e-310 6.94843113e-310] [6.94843113e-310 6.94843113e-310 6.94843113e-310]]
The values appear random because NumPy does not overwrite memory
when using np.empty.
Key Differences
| Aspect | np.zeros | np.empty |
|---|---|---|
| Initialization | All values set to 0 | Uninitialized (random memory values) |
| Predictability | Fully predictable | Unpredictable |
| Performance | Slightly slower | Faster |
| Typical Use | Clean starting state | Immediate overwrite |
When Should You Use Each?
- Use np.zeros when you need a safe, known baseline for calculations.
- Use np.empty when performance matters and you plan to assign all values immediately.
๐ก Key Takeaways
np.zerosguarantees clean initializationnp.emptyskips initialization for speed- Uninitialized arrays may contain garbage values
- Choose based on safety vs performance needs
- Never rely on values from
np.emptywithout overwriting them