DataLens

Creating arrays (array, arange, zeros, ones, linspace)

Build arrays from lists, number ranges, evenly spaced points and filled grids, the starting point of every NumPy program.

Level: Foundations · 8 min read

Practise this module

The questions for this lesson run in your browser and check your answer straight away.

The idea

Before you can calculate, you need an array. Sometimes the numbers come from data (a list, a file, a pandas column). Often you need to generate them: the days of a month, 100 evenly spaced points for a chart, a grid of zeros to fill in later. NumPy has a function for each.

From a list: np.array

When you already have the numbers, like a week of daily order counts, pass them to np.array as a list:

import numpy as np

daily_orders = np.array([42, 38, 51, 47, 60, 75, 68])
print(daily_orders)
[42 38 51 47 60 75 68]

A list of lists becomes a 2-D array, a grid with rows and columns. Each inner list is one row, and all rows must have the same length:

# units sold: rows = stores, columns = months (Jan to Jun)
units = np.array([
    [120, 135, 150, 160, 155, 170],   # Jakarta
    [ 80,  85,  90,  88,  95, 100],   # Bandung
    [ 95,  92, 105, 110, 108, 115],   # Surabaya
])
print(units)
[[120 135 150 160 155 170]
 [ 80  85  90  88  95 100]
 [ 95  92 105 110 108 115]]

That's the shape of most data you'll handle: a table of numbers. A 2-D array is exactly what sits under a pandas DataFrame of numbers.

Ranges: np.arange

Often you need a sequence of numbers rather than data you already have: day numbers 1 to 31, order ids, or every tenth value for a chart axis. np.arange is NumPy's version of range, but it gives you an array:

print(np.arange(5))            # 0 to 4
print(np.arange(1, 8))         # 1 to 7
print(np.arange(0, 50, 10))    # step of 10
[0 1 2 3 4]
[1 2 3 4 5 6 7]
[ 0 10 20 30 40]

Like range, the stop is excluded: np.arange(1, 8) ends at 7. Unlike range, it also accepts decimals:

print(np.arange(0, 1, 0.25))
[0.   0.25 0.5  0.75]
Warning

With decimal steps, rounding can make arange include or skip the last value unexpectedly (0.1 can't be stored exactly in binary). When you want "N points between A and B", use linspace instead.

Evenly spaced points: np.linspace

np.linspace(start, stop, num) gives num points from start to stop, including both ends:

print(np.linspace(0, 1, 5))
print(np.linspace(100, 200, 3))
[0.   0.25 0.5  0.75 1.  ]
[100. 150. 200.]

You choose how many points, and NumPy works out the spacing. That's what you want for charts ("draw this curve with 100 points") and for scenarios ("try 5 discount levels from 0% to 40%"):

discounts = np.linspace(0, 0.4, 5)
price = 320
print(discounts)
print(price * (1 - discounts))
[0.  0.1 0.2 0.3 0.4]
[320. 288. 256. 224. 192.]

Filled arrays: zeros, ones, full

To create an array of a given shape filled with one value:

print(np.zeros(4))
print(np.ones((2, 3)))
print(np.full((2, 4), 7))
[0. 0. 0. 0.]
[[1. 1. 1.]
 [1. 1. 1.]]
[[7 7 7 7]
 [7 7 7 7]]

Why create a grid of zeros? To fill it in later, for example a stores × weeks table that you complete as data arrives. You'll learn to assign into arrays in the indexing module.

Each has a _like version that copies the shape of an existing array:

targets = np.full_like(units, 100)
print(targets)
[[100 100 100 100 100 100]
 [100 100 100 100 100 100]
 [100 100 100 100 100 100]]

Choosing the type: dtype

Every creation function accepts dtype= to choose the element type:

print(np.zeros(3, dtype=int))
print(np.array([1, 2, 3], dtype=float))
print(np.arange(3, dtype=np.float32))
[0 0 0]
[1. 2. 3.]
[0. 1. 2.]

The next module explains dtypes in detail.

Why this matters for clean code

Generating numbers with the right function says what you mean: np.linspace(0, 0.4, 5) is clearly "5 evenly spaced discounts", while a hand-typed [0, 0.1, 0.2, 0.3, 0.4] invites typos and has to be retyped when you want 9 levels. Prefer functions that compute your inputs over values typed by hand.

Recap

Practise this module

The questions for this lesson run in your browser and check your answer straight away.

Next: Array attributes (shape, dtype, ndim) →