Generating Arrays (arange, linspace, zeros, ones)
NumPy offers built-in functions that let you create arrays quickly without typing values manually.
These functions are especially useful for generating test data or initializing arrays for computations.
np.arange(start, stop, step)
Generates evenly spaced values from start to stop (excluding stop).
np.arange(start, stop, step)
np.arange(0, 10, 2) # [0 2 4 6 8]
np.linspace(start, stop, num)
Generates a specific number of evenly spaced values including the stop value.
np.linspace(start, stop, num)
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.0]
np.zeros(shape) and np.ones(shape)
Create arrays filled with zeros or ones.
Pass a shape like (3,) or (2, 3).
np.zeros(shape)
np.zeros((2, 2))
# [[0. 0.]
# [0. 0.]]
np.ones(shape)
np.ones((2, 3))
# [[1. 1. 1.]
# [1. 1. 1.]]
Summary
arange: values spaced by step (likerange())linspace: values spaced by number of pointszeros/ones: fill arrays with fixed values
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.