Sub topic 1
What an ndarray Is and Why It Differs from a Python List
Prerequisites
Assume you know basic Python lists, loops, functions, and arithmetic. You should also be comfortable running code in a script or notebook.
The ndarray model
A NumPy ndarray is a fixed-shape, multidimensional array whose elements share one data type. Unlike a Python list, it stores values in a compact, typed block of memory. This design lets NumPy apply one operation to many values without a Python loop.
flowchart LR
L[Python list<br/>mixed objects] --> C[General-purpose container]
N[NumPy ndarray<br/>same dtype and shape] --> V[Vectorized numerical computation]Creating and inspecting arrays
Use np.array for existing data. Functions such as zeros, arange, and linspace create regular arrays.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
zeros = np.zeros((2, 3))
steps = np.arange(0, 10, 2)
points = np.linspace(0, 1, 5)
print(a.shape, a.ndim, a.size, a.dtype)
# (2, 3) 2 6 int64shape describes the length along each dimension. ndim is the number of dimensions. size is the total number of elements. The exact default integer dtype can vary by platform.
| Expression | Meaning |
|---|---|
| `a.shape` | Two rows and three columns |
| `a.ndim` | Two dimensions |
| `a.size` | Six elements |
| `a.dtype` | The element data type |
Data types and casting
An array normally has one dtype. NumPy may choose a common type when it creates an array from mixed numeric values. Use astype to create an array with another type.
values = np.array([1.7, 2.9, 3.1])
integers = values.astype(np.int64)
print(integers) # [1 2 3]Casting from floating point to an integer truncates toward zero. It does not round to the nearest integer.
> callout note > Check dtype when precision, storage size, or integer overflow matters.
Indexing and slicing
Indexing selects one element. A slice selects a range along an axis. For a two-dimensional array, provide one index per dimension.
a = np.arange(12).reshape(3, 4)
print(a[1, 2]) # 6
print(a[0, 1:3]) # [1 2]
print(a[:, 0]) # [0 4 8]The slice : means “all positions” on that axis. Unlike a list, an ndarray supports multidimensional indexing directly.
Exercise
What are the shape, ndim, and size of np.zeros((4, 2, 3))?
Show answer
The shape is (4, 2, 3), ndim is 3, and size is 24.