Creating numpy arrays with fixed values

Martin McBride, 2019-09-15
Tags arrays, data types
Categories numpy
In section Python libraries

In this section we will look at how to create numpy arrays with fixed content (such as all zeros).

Here is a video covering this topic:

We will first look at the zeros function, that creates an array full of zeros. We will use that to see how to:

  • Create arrays of different shapes.
  • Create arrays using different data types (such as floats and ints).
  • Create like arrays (arrays that copy the shape and type of another array).

We will the look at some other fixed value functions: ones, full, empty, identity.

zeros function

The zeros function creates a new array containing zeros. For example:

import numpy as np

a1 = np.zeros(4)

This will create a1, one dimensional array of length 4. By default the array will contain data of type float64, ie a double float (see data types).

[ 0.  0.  0.  0.]

Creating zero arrays of different shape

The shape of an array specifies the number of dimensions and the size of the array in each dimension. For example a shape of (2, 3) specifies a 2 dimensional array consisting of 2 rows of 3 columns:

a2 = np.zeros((2, 3))

Here is the output:

[[ 0.  0.  0.]
 [ 0.  0.  0.]]

The shape of the array is often specified by a tuple eg (2, 3). Of course you can use a list, or any other sequence of integers (even another numpy array if you want to).

For one dimensional arrays, you can optionally use a single integer, rather than a tuple of one item - this is what we did when we created a1 above.

Setting the data type

By default, the array is created with a data type of float64. You can use the optional parameter dtype to specify a different data type. For a numpy array, all the elements must be the same type.

In the code below, a2_ints is an integer array. See the article on data types for a full list of data types:

a3 = np.zeros((2, 2), dtype=np.int32)

This gives:

[[0 0]
 [0 0]]


The zeros_like function will create a new array of zeros that is the same shape and data type as the supplied array:

b1 = np.array([[1, 2], [3, 4]])
c1 = np.zeros_like(a2_ints)

c1 now contains a new 2 by 2 array of integer zeros.


The ones function is exactly the same as zeros, except that it fills the array with value 1. For example:

o1 = np.ones((3, 2))


[[1. 1.]
 [1. 1.]
 [1. 1.]]

You can choose the select the type, in the same way as zeros. There is also a ones_like function that works in an analogous way to zeros_like.


The empty function is also similar to zeros, except that it leaves the data array uninitialised. empty might be slightly faster than zeros, so it can be used if you are intending to immediately initialise the array in some other way.

Bear in mind that the uninitialised memory might not be random. It will just be whatever happens to be in the memory, so it might potentially contain user data left behind from the last time the memory was used.

There is, of course, a corresponding empty_like function.


The full function takes an extra parameter, the fill value, and uses that value to initialise the array elements:

f1 = np.full((2, 3), 7)


[[ 7.  7.  7.]
 [ 7.  7.  7.]]

Again, there is also a full_like function:

b1 = np.array([[1, 2], [3, 4]])
f2 = np.full_like(b1, 3)


[[3 3]
 [3 3]]


The identity function creates an identity matrix. This is always a square, 2-dimensional array. You just need to specify the size and optional type:

i = np.identity(3)

This creates a 3 by 3 array with the diagonal elements set to 1 and everything else set to 0:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

You can also checkout the eye function, which also creates a diagonal matrix, but with extra control (for example, creating a non-square array).

Visit the PythonInformer Discussion Forum for numeric Python.

If you found this article useful, you might be interested in the book NumPy Recipes, or other books, by the same author.


Popular tags

2d arrays abstract data type alignment and animation arc array arrays bezier curve built-in function circle close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary drawing duck typing efficiency encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools koch curve l system lambda function len line linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path polygon positional parameter print pure function pycairo radial gradient range recipes rectangle recursion reduce rgb rotation scaling sector segment sequence slice slicing sound spirograph sprite square str stream string stroke subpath symmetric encryption template text text metrics transform translation transparency tuple turtle unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020