Unlike np.zeros() or np.ones(), np.empty() skips the step of writing initial values into the allocated memory entirely, which makes it marginally faster to create, but means its contents are unpredictable garbage — whatever bytes happened to be in that memory already, possibly leftover data from a previous, unrelated array. It only makes sense to use when you're certain every element will be overwritten before it's ever read, such as immediately before a loop that fills in every index.
1Understanding np.empty()
Unlike np.zeros() or np.ones(), np.empty() skips the step of writing initial values into the allocated memory entirely, which makes it marginally faster to create, but means its contents are unpredictable garbage — whatever bytes happened to be in that memory already, possibly leftover data from a previous, unrelated array. It only makes sense to use when you're certain every element will be overwritten before it's ever read, such as immediately before a loop that fills in every index.
Never read from an np.empty() array before writing to every element — its initial contents are genuinely undefined garbage, not zeros, and can even change between runs of the same program.
import numpy as np
arr = np.empty(3)
print(arr.shape)
print(arr.dtype)2Practical Example
Here is a real-world application of np.empty() showing how it is used in production NumPy code.
import numpy as np
arr = np.empty(5)
for i in range(5):
arr[i] = i ** 2
print(arr)3Best Practices
Follow these guidelines when working with np.empty():
1. Use np.empty() only when you will overwrite every single element before reading any of them, such as right before a fill loop
2. Prefer np.zeros() by default unless you've specifically measured that np.empty()'s tiny initialization-skipping speedup matters for your use case
3. Never rely on np.empty()'s initial values for any logic — treat them as completely undefined
Tip: Never read from an np.empty() array before writing to every element — its initial contents are genuinely undefined garbage, not zeros, and can even change between runs of the same program.
import numpy as np
arr = np.empty(3)
print(arr.shape)
print(arr.dtype)