Lecture

Generating Arrays (arange, linspace, zeros, ones)

NumPy provides built-in functions to quickly create arrays without manually typing values.

These are especially useful for building test data or initializing arrays.


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 (like range())
  • linspace: values spaced by number of points
  • zeros / ones: fill arrays with fixed values
Quiz
0 / 1

Using NumPy's array creation functions

The `np.linspace` function is used to create spaced values, including the final value.
randomly
evenly
randomly with a step
unevenly

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help