TExcelTAD
Home › NumPy › NumPy Creating Arrays

NumPy Creating Arrays

The NumPy array type is called ndarray ("n-dimensional array"). The most common way to create one is to pass a Python list (or tuple) to np.array():

python · try it yourself
import numpy as np

from_list = np.array([10, 20, 30])
from_tuple = np.array((1.5, 2.5))
print(from_list, type(from_list))
print(from_tuple)
[10 20 30] <class 'numpy.ndarray'>
[1.5 2.5]

Dimensions

A dimension (also called an axis) is one direction you can move through the data. Nested lists create arrays with more dimensions:

Dimensions Name Example Real-world picture
0-D scalar np.array(7) a single reading
1-D vector np.array([1, 2, 3]) one row of values
2-D matrix np.array([[1, 2], [3, 4]]) a spreadsheet table
3-D tensor np.array([[[1], [2]], [[3], [4]]]) a stack of tables, e.g. RGB image

The ndim attribute tells you how many dimensions an array has:

python · try it yourself
import numpy as np

scalar = np.array(7)
vector = np.array([1, 2, 3])
matrix = np.array([[1, 2, 3],
                   [4, 5, 6]])
cube = np.array([[[1, 2], [3, 4]],
                 [[5, 6], [7, 8]]])

for name, arr in [("scalar", scalar), ("vector", vector), ("matrix", matrix), ("cube", cube)]:
    print(f"{name:7} ndim={arr.ndim} shape={arr.shape}")
print(cube)
scalar  ndim=0 shape=()
vector  ndim=1 shape=(3,)
matrix  ndim=2 shape=(2, 3)
cube    ndim=3 shape=(2, 2, 2)
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

When NumPy prints a 3-D array, it shows each 2-D "layer" separated by a blank line.

Note: Nested lists must be rectangular. np.array([[1, 2], [3]]) raises a ValueError in NumPy 2, because rows of different lengths can't form a grid.

You can also ask for extra dimensions directly with ndmin, which pads the shape with leading 1s:

python · try it yourself
import numpy as np

arr = np.array([4, 5, 6], ndmin=3)
print(arr)
print("ndim:", arr.ndim, "shape:", arr.shape)
[[[4 5 6]]]
ndim: 3 shape: (1, 1, 3)

Built-in constructors

Typing every value by hand is rarely practical. NumPy has functions that build arrays from a recipe:

Function Creates
np.zeros(shape) all zeros
np.ones(shape) all ones
np.full(shape, value) every element = value
np.eye(n) identity matrix (1s on the diagonal)
np.arange(start, stop, step) evenly spaced values, stop excluded (like range)
np.linspace(start, stop, num) num evenly spaced values, stop included
np.empty(shape) uninitialised memory (fast, but contents are garbage)
python · try it yourself
import numpy as np

print(np.zeros(4))
print(np.ones((2, 3), dtype=int))
print(np.full((2, 2), 7))
print(np.eye(3))
print(np.arange(0, 20, 5))
print(np.linspace(0, 1, 5))
[0. 0. 0. 0.]
[[1 1 1]
 [1 1 1]]
[[7 7]
 [7 7]]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
[ 0  5 10 15]
[0.   0.25 0.5  0.75 1.  ]

Notice that np.zeros(4) gives floats (0.): the default type for these constructors is float64. Pass dtype=int to get integers.

arange vs linspace is a frequent question. Use arange when you know the step (every 5 minutes), and linspace when you know how many points you want between two ends (100 points for a smooth plot).

Arrays shaped like other arrays

np.zeros_like(a), np.ones_like(a) and np.full_like(a, v) copy the shape and type of an existing array, which is handy for preparing a result container:

python · try it yourself
import numpy as np

scores = np.array([[70, 85], [90, 60]])
bonus = np.full_like(scores, 5)
print(bonus)
print(scores + bonus)
[[5 5]
 [5 5]]
[[75 90]
 [95 65]]

Test yourself

What does np.array([[1, 2, 3], [4, 5, 6]]).ndim return?

  1. 1
  2. 2
  3. 3
  4. 6

Which call gives [0. 0.25 0.5 0.75 1.]?

  1. np.arange(0, 1, 0.25)
  2. np.linspace(0, 1, 5)
  3. np.linspace(0, 1, 4)
  4. np.zeros(5)

What is the default dtype of np.zeros(3)?

  1. int64
  2. float64
  3. bool
  4. object