Module 1 · Beginner · Getting started with NumPy

How to create NumPy arrays, with examples

Create NumPy arrays from lists, or with zeros, ones, full, arange, linspace, eye and random numbers, with examples, practice and interview questions.

By theprogrammers team · · 5 min read

Before you can do anything with NumPy, you need an array. You can build one from a Python list, but most of the time you'll ask NumPy to create it for you: an array of zeros to fill in later, a range of evenly spaced numbers for a chart, or random numbers for a simulation.

This lesson shows every common way to create a NumPy array, explains when to use each one, and points out the mistakes beginners make with arange and linspace.

If you haven't used NumPy before, read the NumPy array tutorial for beginners first.

Creating an array from a list

Pass a list to np.array. A list of lists makes a 2D array, with one inner list per row:

import numpy as np

marks = np.array([72, 85, 91, 64])
print(marks)          # [72 85 91 64]

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])
print(grid.shape)     # (2, 3): 2 rows, 3 columns

Every row must have the same length. A ragged list such as [[1, 2], [3]] raises a ValueError, because an array is always a neat rectangle.

If you mix integers and floats, NumPy converts everything to the more general type:

print(np.array([1, 2.5, 3]))    # [1.  2.5 3. ]

Arrays of zeros, ones or any value

When you know the size but not the values yet, create a placeholder and fill it in later. Pass the shape as a number, or as a tuple for more dimensions:

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

Notice that zeros and ones give floats by default (the dot after each number). Ask for whole numbers with dtype:

counts = np.zeros(5, dtype=int)
print(counts)          # [0 0 0 0 0]

There are also np.zeros_like(a) and np.ones_like(a), which make a new array with the same shape and type as an existing one. They save you from typing the shape again.

Ranges with arange

np.arange works like Python's range, but returns an array. The stop value is not included:

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

Unlike range, arange accepts decimal steps. But be careful: decimals aren't stored exactly in a computer, so with a decimal step you can get one value more or fewer than you expect. For decimal ranges, use linspace instead.

Evenly spaced numbers with linspace

np.linspace(start, stop, num) gives you exactly num values from start to stop, including the stop value:

print(np.linspace(0, 1, 5))    # [0.   0.25 0.5  0.75 1.  ]

You say how many points you want, and NumPy works out the gap. This is perfect for charts: x = np.linspace(0, 10, 100) gives 100 smooth points to plot a curve.

arangelinspace
You giveThe step sizeThe number of values
Includes the stop valueNoYes, by default
Best forWhole-number rangesDecimal ranges and charts

Identity matrices with eye

np.eye(n) makes a square matrix with ones on the diagonal and zeros elsewhere. It's the "1" of matrix maths, and you'll meet it in linear algebra for machine learning:

print(np.eye(3))
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Random numbers

Simulations, games, and splitting data for machine learning all need random numbers. Create a random generator first, then ask it for numbers. Giving it a seed (any fixed number) makes the "random" numbers the same every time you run the code, which makes results repeatable:

rng = np.random.default_rng(seed=42)

print(rng.integers(1, 7, size=5))     # 5 dice rolls: 1 to 6
print(rng.random(3))                  # 3 floats between 0 and 1
print(rng.normal(170, 10, size=3))    # 3 heights, mean 170, std 10
[1 5 4 3 3]
[0.69736803 0.09417735 0.97562235]
[171.27840403 166.83757408 169.83198842]

As with arange, the high value in integers isn't included, so integers(1, 7) means 1 to 6.

You may see older code using np.random.randint and np.random.seed. They still work, but default_rng is the recommended way in new code.

Arrays from a file

Real data usually comes from a file. np.loadtxt reads simple numeric text files such as CSVs:

data = np.loadtxt("marks.csv", delimiter=",", skiprows=1)

skiprows=1 skips the header line. For files with text columns or missing values, use pandas instead: see the pandas DataFrame tutorial.

Which function should I use?

You wantUse
An array from data you already havenp.array(list)
A placeholder to fill in laternp.zeros, np.ones, np.full
Whole numbers in stepsnp.arange
A fixed number of points for a chartnp.linspace
An identity matrixnp.eye
Random numbersnp.random.default_rng(seed)

Practice

  1. Create an array of the even numbers from 10 to 30, including 30.
Show the answer
print(np.arange(10, 31, 2))
# [10 12 14 16 18 20 22 24 26 28 30]

The stop value is excluded, so use 31 (or 32) to include 30.

  1. Create a 3 × 4 array filled with the number 5, as whole numbers.
Show the answer
print(np.full((3, 4), 5))

np.full keeps the type of the fill value, so 5 gives integers. np.ones((3, 4), dtype=int) * 5 also works.

  1. Make 11 evenly spaced values from 0 to 1, then simulate 10 coin tosses as 0s and 1s.
Show the answer
print(np.linspace(0, 1, 11))    # 0.0, 0.1, ... 1.0
rng = np.random.default_rng(1)
print(rng.integers(0, 2, size=10))

integers(0, 2) gives 0 or 1, because 2 is excluded.

Interview questions

What is the difference between np.arange and np.linspace?

arange(start, stop, step) takes a step size and excludes the stop value; with decimal steps, rounding can change how many values you get. linspace(start, stop, num) takes the number of values and includes the stop by default, so it's the safer choice for decimal ranges.

Why does np.zeros(3) return floats?

The default dtype for zeros, ones and empty is float64, because most numerical work uses decimals. Pass dtype=int to get integers.

Why should you set a random seed?

A seed makes the random numbers repeatable. Anyone running your code gets the same results, which makes debugging, teaching and machine learning experiments reproducible.

What does np.empty do, and when is it risky?

np.empty(shape) allocates an array without setting its values, so it contains whatever was already in that memory. It's slightly faster than zeros, but only safe if you overwrite every value before reading it.

What to learn next

  1. Learn what types an array can hold in NumPy data types (dtype) explained.
  2. Pick out values with NumPy indexing and slicing.