arange
import numpy as np print(np.arange(5)) print(np.arange(2, 12, 3)) print(np.arange(0, 1, 0.25))
Write Python. Understand every error.
NumPy · topic 18 of 25
You rarely type every value by hand. NumPy has functions that build arrays for you.
np.arange(start, stop, step) works like range() but returns an array, and the step can be a decimalnp.linspace(start, stop, num) gives num evenly spaced values, and it includes stopnp.zeros(shape), np.ones(shape) and np.full(shape, value) fill an array with one valuenp.eye(n) is the identity matrix: ones on the diagonal, zeros elsewhereprint(np.arange(0, 10, 2)) # [0 2 4 6 8] print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
For more than one dimension, pass the shape as a tuple, such as np.zeros((2, 3)). These functions produce floats by default; add dtype=int for whole numbers.
A very common pattern is to create a 1D sequence and then give it a new shape with reshape. The number of elements must stay the same, and one dimension can be -1, meaning "work this out for me".
grid = np.arange(1, 13).reshape(3, 4) print(grid)
For random data, create a generator with a seed so your results can be repeated: rng = np.random.default_rng(42), then use rng.integers(low, high, size) or rng.random(size).
np.arange(start, stop, step) works like range() but returns an array, and the step can be a decimal.np.linspace(start, stop, num) gives num evenly spaced values and includes the stop value.np.zeros, np.ones and np.full fill an array of a given shape with one value, and np.eye(n) is the identity matrix.np.zeros((2, 3)) for 2 rows and 3 columns.np.zeros(2, 3) instead of np.zeros((2, 3)). The shape is a single tuple. Read the TypeError guide.arange to include the stop value. It does not, but linspace does.
import numpy as np print(np.arange(5)) print(np.arange(2, 12, 3)) print(np.arange(0, 1, 0.25))
import numpy as np print(np.linspace(0, 1, 5)) print(np.linspace(10, 20, 3))
import numpy as np print(np.zeros(4)) print(np.ones((2, 3), dtype=int)) print(np.full((2, 2), 7))
import numpy as np print(np.eye(3))
import numpy as np grid = np.arange(1, 13).reshape(3, 4) print(grid) print(np.arange(10).reshape(2, -1))
import numpy as np rng = np.random.default_rng(42) print(rng.integers(1, 7, size=5)) # five dice rolls print(rng.random(3)) # Values differ from real NumPy, but the same seed always gives the same values here.
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np print(np.arange(0, 10, 3))
arange works like range: start 0, step 3, stop before 10.
import numpy as np print(np.zeros(3))
zeros gives floats by default, printed as 0.
import numpy as np print(np.linspace(0, 1, 5))
linspace gives 5 evenly spaced values including both ends.
import numpy as np print(np.ones((2, 3)).sum())
A 2 by 3 array of ones has 6 ones.
np.arange(5) contain?Like range(5), it starts at 0 and stops before 5.