Creating arrays

NumPy · Essentials · 8 min

Real code preallocates buffers, makes coordinate grids and test data far more often than it types literal lists.

Besides np.array(list), NumPy has constructors that create arrays of a given shape directly. They all take a shape (an int or a tuple) and an optional dtype:

  • np.zeros(shape), np.ones(shape): filled with 0 or 1, float64 by default
  • np.full(shape, value): filled with any value
  • np.empty(shape): allocated but not initialised; it contains whatever bytes were in memory. Use it only when you will overwrite every element.
  • np.eye(n): identity matrix

For ranges there are two tools that look similar but answer different questions. np.arange(start, stop, step) works like Python's range (stop excluded) but returns an array and accepts float steps. np.linspace(start, stop, num) gives exactly num evenly spaced points and includes stop by default. Prefer linspace for floats: with arange(0, 1, 0.1) rounding error can make the number of elements surprising.

The *_like family copies shape and dtype from an existing array: np.zeros_like(a), np.ones_like(a), np.full_like(a, 7). This is handy for building an output buffer that matches an input.

np.asarray(x) converts to an array only if needed, returning x itself when it already is a suitable ndarray, whereas np.array(x) copies by default. In NumPy 2, np.array(x, copy=False) means "never copy" and raises if a copy is unavoidable, so use np.asarray for "copy only if necessary".

Example

import numpy as np

print(np.zeros((2, 3)))          # 2x3 of 0.0
print(np.full(3, 7))             # [7 7 7]
print(np.eye(2, dtype=int))      # [[1 0] [0 1]]

print(np.arange(5))              # [0 1 2 3 4]
print(np.arange(2, 10, 3))       # [2 5 8]
print(np.linspace(0, 1, 5))      # [0.   0.25 0.5  0.75 1.  ]

a = np.array([[1, 2], [3, 4]])
b = np.zeros_like(a)             # int array of zeros, shape (2, 2)
print(b.dtype, b.shape)          # int64 (2, 2)

c = np.asarray(a)
print(c is a)                    # True  -- no copy made

Remember

  • zeros, ones, full, empty take a shape and optional dtype
  • arange excludes stop and steps by size; linspace gives a fixed count and includes stop
  • np.asarray avoids needless copies; *_like mirrors an existing array

Watch out for

  • Reading values from np.empty before writing them: the contents are garbage, not zeros.

Check yourself

  1. You need exactly 11 evenly spaced floats from 0 to 1 inclusive. Which call is the right tool?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: numpy.org/doc/stable/user/basics.creation.html