CodeMIRAI
0 XP

Creating arrays

2 min read 5 runnable examples Quiz included

From a list

Python
import numpy as np

a = np.array([3, 1, 4, 1, 5])
b = np.array([[1, 2, 3],
              [4, 5, 6]])          # a 2D array from a list of lists
print(a)
print(b)

Built-in constructors

Python
import numpy as np

print(np.zeros(5))                # five 0.0s
print(np.ones((2, 3)))            # 2 rows, 3 columns of 1.0
print(np.full((2, 2), 7))         # filled with 7
print(np.arange(0, 20, 5))        # like range(): 0, 5, 10, 15
print(np.linspace(0, 1, 5))       # 5 evenly spaced values from 0 to 1
print(np.eye(3))                  # identity matrix

arange steps by a fixed amount; linspace gives an exact number of points, including the end.

Shape, size, dimensions and type

Python
import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
print("shape:", m.shape)     # (rows, columns)
print("ndim: ", m.ndim)      # number of dimensions
print("size: ", m.size)      # total elements
print("dtype:", m.dtype)     # element type
a = np.arange(12).reshape(3, 4) · a.shape == (3, 4)01234567891011axis 0: rowsaxis 1: columnsa.sum(axis=0) adds downthe rows: one per columna[1] is the middle row
Shape lists the size along each axis. Axis 0 runs down the rows, axis 1 across the columns.

dtype: one type for every element

Python
import numpy as np

print(np.array([1, 2, 3]).dtype)
print(np.array([1.5, 2, 3]).dtype)       # one float makes them all float
print(np.array([1, 2, 3], dtype=float))
print(np.array([1.9, 2.7]).astype(int))  # astype converts (and truncates)

Random arrays

Python
import numpy as np

rng = np.random.default_rng(seed=42)    # a seed makes results repeatable
print(rng.integers(1, 7, size=10))      # ten dice rolls
print(rng.random(3))                     # three floats in [0, 1)
print(rng.normal(170, 8, size=4).round(1))   # heights: mean 170, sd 8
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.