Sub topic 1
What an ndarray is and why it differs from a Python list
Prerequisites
This chapter assumes you can write basic Python (lists, loops, functions) and run code in a script or notebook. It also assumes you know roughly what a vector and a matrix are. You need NumPy installed (pip install numpy).
The working model
An ndarray (n-dimensional array) is NumPy's core object. It is a block of memory that holds values of one type, laid out in a fixed shape. Three properties define it:
- Homogeneous: every element has the same data type (dtype).
- Fixed-size: the shape is set when the array is created. Changing the number of elements means building a new array.
- N-dimensional: the same object represents a vector, a matrix, or higher-dimensional data.
A Python list works differently. It stores pointers to separate Python objects, and each object carries its own type and reference count. An ndarray stores the raw values next to each other, with one dtype describing all of them.
This design has two consequences. Memory use is smaller, because there is no per-element object overhead. Computation is faster, because NumPy runs compiled loops over the contiguous block instead of running Python bytecode for each element.
A first array
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 systemsshape is a tuple with the length of each axis. ndim is the number of axes. size is the total element count. dtype is the type shared by all elements. The exact default integer type depends on the platform, so do not rely on int64 everywhere.
Lists versus arrays in practice
The difference shows up as soon as you do arithmetic.
import numpy as np
nums = [1, 2, 3]
arr = np.array([1, 2, 3])
print(nums * 2) # [1, 2, 3, 1, 2, 3] (repetition)
print(arr * 2) # [2 4 6] (elementwise)
print(nums + nums) # [1, 2, 3, 1, 2, 3] (concatenation)
print(arr + arr) # [2 4 6]The operators mean different things. On a list, * repeats and + concatenates. On an array, they apply to each element.
Because an array has one dtype, mixed input is converted to a common type:
import numpy as np
print(np.array([1, 2.5, 3])) # [1. 2.5 3. ] ints become floats
print(np.array([1, "a"])) # ['1' 'a'] everything becomes a stringCommon errors
- Expecting
+to join arrays. Usenp.concatenatefor that, which a later chapter covers. - Mixing types and getting a surprise. Check
arr.dtypewhen results look odd. A string in the input turns the whole array into strings. - Appending to an array in a loop. Arrays have a fixed size, so each append builds a new array. Collect values in a list and convert once, or create the array at its final size first.
- Passing separate arguments instead of one sequence.
np.array(1, 2, 3)raises an error. Writenp.array([1, 2, 3]).
Exercise
What is the result of np.array([1, 2, 3]) + np.array([10, 20, 30]), and what does [1, 2, 3] + [10, 20, 30] produce? Explain why they differ.
Show answer
The array expression gives array([11, 22, 33]), because + on ndarrays adds elementwise. The list expression gives [1, 2, 3, 10, 20, 30], because + on lists concatenates them. The operator is defined by the type of the object.
Exercise
Predict the dtype of np.array([1, 2.5, True]), then explain why.
Show answer
It is float64. All elements must share one dtype, so NumPy picks a type that can hold every value. The integer and the boolean convert to floats (1.0 and 1.0), giving [1. , 2.5, 1. ].