Creating arrays

Intermediate

Introduction

Before you can compute with arrays you need to make them. Real data usually arrives from a file, but programs constantly need arrays of their own: a grid of zeros to fill in, the numbers 0 to 99, a hundred points between 0 and 1 to evaluate a function at, an identity matrix. NumPy has a small set of creation functions that cover nearly every case, and knowing exactly what each one returns saves many off-by-one errors.

How it works

np.array turns a list, or a list of equal-length lists, into an array, copying the values:

np.array([1, 2, 3])          # array([1, 2, 3])
np.array([[1, 2], [3, 4]])   # a 2 x 2 array

Filled arrays take a shape, an integer for 1-D or a tuple for more dimensions:

np.zeros(3)                  # array([0., 0., 0.])
np.ones((2, 2), dtype=int)   # array([[1, 1],
                             #        [1, 1]])
np.full((2, 3), 7)           # 2 x 3, every value 7
np.eye(2)                    # array([[1., 0.],
                             #        [0., 1.]])

Note the dots in 0. and 1.: zeros, ones and eye make floating-point arrays unless you pass dtype=int.

For evenly spaced numbers there are two functions, and the difference matters. np.arange(start, stop, step) works like Python's range: it counts from start in steps of step and stops before stop. np.arange(0, 10, 3) gives array([0, 3, 6, 9]). np.linspace(start, stop, num) instead takes how many values you want, and includes the stop: np.linspace(0, 1, 5) gives array([0. , 0.25, 0.5 , 0.75, 1. ]). Use arange with whole-number steps, and linspace when you need an exact number of points between two ends, especially with fractions, where a floating-point step in arange can give one value more or fewer than you expect.

Every creation function takes a dtype argument, such as dtype=float or dtype=np.int32, which the next lesson covers.

Example

# Models of NumPy's array creators: arange, linspace, zeros, ones and eye.
def arange(start, stop, step=1):
    values, x = [], start
    while (step > 0 and x < stop) or (step < 0 and x > stop):
        values.append(x)
        x += step
    return values

def linspace(start, stop, num):
    step = (stop - start) / (num - 1)
    return [start + i * step for i in range(num)]

def full(rows, cols, value):
    return [[value] * cols for _ in range(rows)]

def eye(n):
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]

print("arange(0, 10, 3):", arange(0, 10, 3))
print("arange(5, 0, -2):", arange(5, 0, -2))
print("linspace(0, 1, 5):", linspace(0, 1, 5))
print("zeros((2, 3)):", full(2, 3, 0))
print("ones((2, 2)):", full(2, 2, 1))
print("eye(3):", eye(3))
Open in compiler

Line by line

  1. arange counts from the start in steps until it reaches the stop, which is never included; a negative step counts down.
  2. linspace works out the step from the number of points, so the stop is the last value.
  3. full builds a grid of one value; zeros and ones are the special cases 0 and 1.
  4. eye puts 1 where the row index equals the column index.

Expected result

arange(0, 10, 3): [0, 3, 6, 9]
arange(5, 0, -2): [5, 3, 1]
linspace(0, 1, 5): [0.0, 0.25, 0.5, 0.75, 1.0]
zeros((2, 3)): [[0, 0, 0], [0, 0, 0]]
ones((2, 2)): [[1, 1], [1, 1]]
eye(3): [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

In the real world

np.zeros makes empty images and buffers to fill; np.linspace makes the x values for plotting a function; np.arange numbers rows and builds index arrays; np.eye appears in linear algebra and in "one-hot" encodings of categories for machine learning.

Common mistakes

  • Passing two numbers instead of a tuple: np.zeros(2, 3) is an error; write np.zeros((2, 3)).
  • Expecting arange to include the stop: np.arange(1, 5) stops at 4.
  • Using arange with a float step and getting one value too many or too few; use linspace.
  • Forgetting that zeros and ones are floats by default.

Best practices

  • Use linspace for fractional spacing and arange for whole-number steps.
  • Write shapes as tuples, even when you could pass separate numbers elsewhere.
  • Pass dtype explicitly when the type matters, for example dtype=int for counters.

Summary

np.array makes arrays from lists. zeros, ones, full and eye make arrays of a given shape tuple, as floats unless a dtype is given. arange steps from a start and excludes the stop; linspace makes a set number of points and includes the stop.

Quick check

1. What does np.arange(1, 10, 4) return?
2. How many values does np.linspace(0, 2, 5) return?
3. What is the dtype of np.zeros(3)?
4. Which call makes a 2 by 3 array of sevens?

Key takeaways

  • np.array copies data from lists; zeros, ones, full and eye make arrays of a given shape.
  • arange takes a step and excludes the stop; linspace takes a count and includes the stop.
  • Shapes are tuples, such as (2, 3); the dtype can be chosen when the array is made.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.