Skip to content
  • NumPy Arrays · Data Science

NumPy Arrays

LearnViaNotes @learnvianotes· 2 min read

NumPy's ndarray stores numbers in one contiguous block of memory with a single type — which makes maths on millions of values fast and concise.

List vs array

Python
import numpy as np
l = [2, 3, 4, 5]
arr = np.array(l)
print(l, type(l).__name__)            # [2, 3, 4, 5] list
print(arr, type(arr).__name__)        # [2 3 4 5] ndarray
print(l * 2)                          # [2, 3, 4, 5, 2, 3, 4, 5]
print(arr * 2)                        # [ 4  6  8 10]

Shape, size and type

Python
import numpy as np
a = np.array([2, 3, 4, 5])
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a.ndim, b.ndim)           # 1 2
print(b.shape, b.size)          # (2, 4) 8
print(b.dtype)                  # int64
AttributeMeaningFor b above
ndimNumber of dimensions (axes)2
shapeLength along each axis — (rows, columns)(2, 4)
sizeTotal number of elements8
dtypeElement typeint64

Creating arrays

Python
import numpy as np
print(np.zeros(3, dtype=int))                # [0 0 0]
print(np.ones((2, 2), dtype=int))            # [[1 1]
                                             #  [1 1]]
print(np.arange(4, 20, 3))                   # [ 4  7 10 13 16 19]
print(np.linspace(2.0, 3.0, num=5))          # [2.   2.25 2.5  2.75 3.  ]
print(np.full(3, 7))                         # [7 7 7]
print(np.eye(2, dtype=int))                  # [[1 0]
                                             #  [0 1]]
FunctionGivesNote
np.zeros(shape) / np.ones(shape)All 0s / all 1sFloat by default — pass dtype=int for ints
np.arange(start, stop, step)Evenly spaced by stepLike range; stop excluded
np.linspace(start, stop, num)Exactly num pointsstop included by default
np.full(shape, v)All v
np.eye(n)Identity matrix

Random numbers

Python
import numpy as np
rng = np.random.default_rng(seed=42)       # the modern API; a seed makes results repeatable
print(rng.random(3).round(3))              # [0.774 0.439 0.859]
print(rng.integers(1, 7, size=5))          # [1 5 2 1 4]
print(rng.normal(0, 1, size=2).round(3))   # [ 0.128 -0.316]

reshape

Python
import numpy as np
arr = np.arange(10)
print(arr.reshape(2, 5))        # [[0 1 2 3 4]
                                #  [5 6 7 8 9]]
print(arr.reshape(5, -1).shape) # (5, 2)   ← -1 means "work it out"
print(np.arange(16).reshape(2, 8, 1).shape)   # (2, 8, 1)

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report