np.zeros/ones/full
These functions make an array pre-filled with zeros, ones or any value you choose.
In this page:
Syntax
np.zeros(shape)
np.ones(shape)
np.full(shape, fill_value)
np.zeros/ones/full
np.zeros and np.ones create arrays of a given shape filled with 0 or 1, and np.full fills with any constant. They are ideal for placeholders and initial values. Pass a tuple for multi-dimensional shapes.
Note:
The default dtype for zeros and ones is float64; pass dtype=int for whole numbers.
Example: np.zeros/ones/full
import numpy as np
print(np.zeros(3))
print(np.ones((2, 3), dtype=int))
print(np.full((2, 2), 7))
# Output:
# [0. 0. 0.]
# [[1 1 1]
# [1 1 1]]
# [[7 7]
# [7 7]]
Related Topics
Common Mistakes
- Passing two numbers instead of one shape tuple
- Forgetting the default dtype is float
- Using np.empty and reading its garbage values
Chapter Summary
- zeros, ones and full pre-fill arrays
- Shape is given as an int or tuple
- Default dtype is float64
- np.full accepts any fill value
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: