Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 18 of 25

Creating arrays

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 decimal
  • np.linspace(start, stop, num) gives num evenly spaced values, and it includes stop
  • np.zeros(shape), np.ones(shape) and np.full(shape, value) fill an array with one value
  • np.eye(n) is the identity matrix: ones on the diagonal, zeros elsewhere
print(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).

Key takeaways

  • 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.
  • The shape is one tuple, for example np.zeros((2, 3)) for 2 rows and 3 columns.

Common mistakes

  • Writing np.zeros(2, 3) instead of np.zeros((2, 3)). The shape is a single tuple. Read the TypeError guide.
  • Expecting arange to include the stop value. It does not, but linspace does.

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.