Sub topic 1
What an ndarray is and why it differs from a Python list
The ndarray (n-dimensional array) is NumPy's core data structure. It looks like a nested list, but it is stored and processed differently. This chapter explains that design. Later chapters on creation, indexing, broadcasting and strides build on it.
Prerequisites
This chapter assumes you have the following:
- Basic Python syntax, including lists, loops and functions.
- A way to run Python code, either a script or a notebook, with NumPy installed (
pip install numpy). - A rough idea of what vectors and matrices are.
All examples use the conventional import import numpy as np.
The working model
An ndarray is a single contiguous block of memory plus a small amount of metadata that says how to interpret that block. The metadata has three parts:
- dtype (data type): how many bytes each element takes and how to read them, for example 64-bit integer or 32-bit float.
- shape: a tuple giving the length along each dimension, such as
(2, 3). - strides: how many bytes to jump to reach the next element along each dimension.
The data buffer holds raw numbers back to back. It does not hold Python objects. The array's three defining properties follow from this design.
- Homogeneous. Every element has the same dtype.
- Fixed size. The element count and shape are set when the array is created.
- N-dimensional. One buffer can be viewed as 1-D, 2-D, 3-D or higher, because shape and strides are only metadata.
You can inspect this metadata directly:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape) # (2, 3)
print(a.ndim) # 2
print(a.size) # 6
print(a.dtype) # int64 on most 64-bit Linux and macOS systemsHow a list is stored
A Python list stores an array of pointers. Each pointer refers to a separate Python object somewhere else on the heap. Every integer in [1, 2, 3] is a full object with a reference count, a type pointer and a value, which takes roughly 28 bytes or more in CPython. Reading an element means following a pointer and then checking the object's type.
An ndarray of 64-bit integers stores 8 bytes per element, laid out one after another. There are no per-element objects, no pointers to follow and no per-element type checks. The array knows its type once, for the whole buffer.
| Property | Python list | NumPy ndarray |
|---|---|---|
| Element storage | Pointers to separate objects | Raw values in one buffer |
| Element types | Can be mixed | One dtype for all elements |
| Bytes per integer | About 8 for the pointer plus about 28 for the object | 8 for int64 |
| Size | Grows with `append` | Fixed at creation |
| Dimensions | Nested lists, any shape | Rectangular, described by shape |
| `+` and `*` | Concatenate and repeat | Elementwise arithmetic |
| Loop speed | Interpreter runs each step | Compiled code runs the loop |
You can measure the memory difference yourself:
import sys
import numpy as np
n = 1_000_000
lst = list(range(n))
arr = np.arange(n)
list_bytes = sys.getsizeof(lst) + sum(sys.getsizeof(x) for x in lst)
print(list_bytes) # roughly 36 million bytes; varies by Python version
print(arr.nbytes) # 8000000 when the default integer is 64-bitThe first number covers the pointer array plus the integer objects. CPython shares some small integers, so the list may use somewhat less than this sum. The gap remains large.
The speed difference comes from the same design. The array's loop runs in compiled C over a contiguous buffer, which also suits the CPU cache:
import timeit
import numpy as np
lst = list(range(1_000_000))
arr = np.arange(1_000_000)
t_list = timeit.timeit(lambda: [x * 2 for x in lst], number=10)
t_arr = timeit.timeit(lambda: arr * 2, number=10)
print(f"list: {t_list:.3f}s ndarray: {t_arr:.3f}s")On typical hardware the array version is tens of times faster. Exact numbers depend on your machine.
Homogeneous: one dtype for everything
When you build an array from mixed values, NumPy picks one dtype that can hold all of them. It does not keep the original types:
import numpy as np
print(np.array([1, 2, 3]).dtype) # int64 on most 64-bit Linux and macOS systems
print(np.array([1, 2.5, 3]).dtype) # float64: the ints were converted
print(np.array([1, "a"]).dtype.kind) # U: everything became a stringThe last case is a common surprise. The integer 1 becomes the string "1", and numeric operations stop working. If you see an unexpected U or O dtype, check your input data.
An array can hold arbitrary Python objects with dtype=object. That array stores pointers again, so it loses most of the speed and memory benefits. Treat object as a fallback, not a feature.
The default integer dtype depends on platform. It is 64-bit on most Linux and macOS systems. On Windows with NumPy 1.x it is 32-bit, and NumPy 2 changed this to 64-bit. Pass dtype= explicitly when the width matters.
Fixed-width integers also wrap around silently when an array operation overflows:
import numpy as np
small = np.array([250], dtype=np.uint8)
print(small + 10) # [4], because 260 wraps modulo 256A Python list never has this problem, since Python integers grow without limit. With an ndarray you choose the width, and you are responsible for it being large enough.
Fixed size: no in-place growth
A list can append cheaply because it over-allocates spare capacity. An ndarray has exactly the memory its shape needs. Functions that look like they grow an array, such as np.append, allocate a new buffer and copy everything:
import numpy as np
a = np.array([1, 2, 3])
b = np.append(a, 4)
print(a) # [1 2 3]
print(b) # [1 2 3 4]Calling np.append in a loop therefore copies the data on every iteration, so the total work grows quadratically. If you do not know the final size, collect results in a list and convert once with np.array(...), or preallocate with np.empty or np.zeros.
N-dimensional and rectangular
A list of lists can have rows of different lengths. An ndarray cannot, because shape is a single tuple that applies to the whole buffer:
import numpy as np
try:
np.array([[1, 2, 3], [4, 5]])
except ValueError as err:
print("ValueError:", err)Modern NumPy raises ValueError here. Older versions silently built a 1-D object array of lists, which hid the problem. If you need ragged data, keep it in a list of arrays.
Indexing also differs. A nested list needs one subscript per level, as in rows[1][2]. An array accepts a comma-separated index, as in a[1, 2]. The next chapters cover this syntax.
Operators mean different things
The ndarray defines operators for numeric work. The same symbols do something else on lists:
import numpy as np
lst = [1, 2, 3]
arr = np.array([1, 2, 3])
print(lst + lst) # [1, 2, 3, 1, 2, 3] concatenation
print(arr + arr) # [2 4 6] elementwise addition
print(lst * 2) # [1, 2, 3, 1, 2, 3] repetition
print(arr * 2) # [2 4 6] elementwise multiplicationApplying one operation to every element without a Python loop is called vectorization. It is the main reason people use NumPy, and a later chapter covers it in full.
Edge cases to remember
- Creating from a list copies.
np.array(lst)copies the values into a new buffer. Later changes tolstdo not affect the array. - Zero-size arrays are valid.
np.array([])has shape(0,)and dtypefloat64. - A scalar array is possible.
np.array(5)has shape()andndim0. - The ndarray is a class. Many NumPy functions accept lists and convert them first. That conversion is a copy, which costs time when repeated.
Exercise
You run x = np.array([10, 20, 30]) and then y = np.append(x, 40). Does x change? Explain what happened in memory.
Show answer
No. x stays [10 20 30]. An ndarray has a fixed size, so np.append allocates a new buffer that holds four elements, copies the old values into it, and returns it as y. The original buffer is untouched.
Exercise
A colleague writes np.array([3, 4.5, "7"]) and then tries arr.sum(). What dtype kind does the array get, and why is the result not what they expect?
Show answer
The array gets dtype kind U (a string type). All elements must share one dtype, and NumPy picks one that can hold every input, which here is a string. The numbers become strings, so numeric reduction no longer works as intended. The fix is to convert the inputs to numbers before building the array.
Exercise
Why does an ndarray of one million 64-bit integers use far less memory than a list of the same numbers?
Show answer
The ndarray stores 8 bytes per value in one contiguous buffer, 8 MB in total. The list stores a pointer for each element and also keeps one separate Python integer object per element, which costs about 28 bytes or more each. The list therefore needs several times as much memory.