ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 6 min read

Array Creation: zeros, ones, arange, linspace & full

Initializing arrays efficiently without memory reallocation

NumPy provides built-in factory functions to allocate multi-dimensional arrays initialized with zeros, ones, constant values, or linear ranges.

Common Array Initialization Functions

np.zeros(shape) and np.ones(shape): Pre-allocates arrays filled with 0s or 1s.

np.arange(start, stop, step): Generates numbers with a fixed step interval, similar to Python range() but returns an ndarray.

np.linspace(start, stop, num): Generates num evenly spaced floating-point samples over a closed interval [start, stop]. Crucial for plotting mathematical curves.

np.full(shape, fill_value): Allocates an array filled with a specific constant.

Using linspace and arange
import numpy as np

# 5 evenly spaced points between 0 and 1 inclusive
linear_pts = np.linspace(0.0, 1.0, num=5)
print("linspace points:", linear_pts)

# Array from 0 up to (not including) 10 with step of 2
stepped = np.arange(0, 10, step=2)
print("arange stepped:", stepped)

# 3x3 identity matrix
identity = np.eye(3)
print("Identity matrix:
", identity)
Array creation routines eliminate the need to initialize empty Python lists and append iteratively.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which NumPy function generates a specified number of evenly spaced points over a specified interval [start, stop]?