Learning Objectives – after this chapter you will be able to:
- Explain what NumPy is and why arrays are faster than lists.
- Create 0-D, 1-D, 2-D and 3-D arrays with
np.array(). - Read the attributes
ndim,shape,sizeanddtype. - Create arrays with
zeros,ones,full,arange,linspaceandeye.
What is NumPy?
- NumPy (Numerical Python) is the core Python library for scientific computing. Its main object is the ndarray – an N-dimensional array of items of the same type.
- It is the foundation of pandas, SciPy, Matplotlib, scikit-learn and many other data-science libraries.
- Install it with
pip install numpy(already installed in Google Colab) and import it asimport numpy as np.
Why arrays instead of lists?
| Basis | Python list | NumPy array |
|---|---|---|
| Item types | Can mix types | All items share one data type (dtype) |
| Memory | Stores references to separate objects | Stores values in one compact, continuous block |
| Speed | Element-wise maths needs Python loops | Vectorised operations run in fast compiled code |
* operator | [1, 2] * 2 → repeats the list | np.array([1, 2]) * 2 → multiplies each item |
import numpy as np prices = [100, 250, 80] arr = np.array(prices) print(prices * 2) # list: repetition print(arr * 2) # array: element-wise maths print(arr + 10) print(type(arr))
Output
[100, 250, 80, 100, 250, 80] [200 500 160] [110 260 90] <class 'numpy.ndarray'>
Creating Arrays of Different Dimensions
0-D Array (a single value)
arr = np.array(42)1D Array
arr = np.array([1, 2, 3, 4, 5, 6])2D Array
arr = np.array([[1, 2, 3, 4, 5, 6], [11, 22, 33, 44, 55, 66]])Multi-Dim (3-D) Array
arr = np.array([[[1, 2, 3], [11, 22, 33]], [[4, 5, 6], [44, 55, 66]]])import numpy as np
a0 = np.array(42)
a1 = np.array([1, 2, 3, 4, 5, 6])
a2 = np.array([[1, 2, 3, 4, 5, 6], [11, 22, 33, 44, 55, 66]])
a3 = np.array([[[1, 2, 3], [11, 22, 33]], [[4, 5, 6], [44, 55, 66]]])
for name, a in [("a0", a0), ("a1", a1), ("a2", a2), ("a3", a3)]:
print(name, "ndim =", a.ndim, "shape =", a.shape, "size =", a.size)
print(a2)Output
a0 ndim = 0 shape = () size = 1 a1 ndim = 1 shape = (6,) size = 6 a2 ndim = 2 shape = (2, 6) size = 12 a3 ndim = 3 shape = (2, 2, 3) size = 12 [[ 1 2 3 4 5 6] [11 22 33 44 55 66]]
| Attribute | Meaning |
|---|---|
ndim | Number of dimensions (axes). |
shape | Tuple giving the size of each dimension, e.g. (rows, columns). |
size | Total number of elements (product of the shape). |
dtype | Data type of the elements, e.g. int64, float64, bool. |
itemsize | Bytes used by one element. |
Data Types (dtype)
All elements have the same type. If you mix integers and floats, NumPy upcasts everything to float. You can set the type with dtype= or convert with astype().
import numpy as np print(np.array([1, 2.5, 3])) # ints upcast to float print(np.array([1, 2, 3], dtype=float)) f = np.array([1.7, 2.2, 3.9]) print(f.dtype, f.astype(int)) # astype truncates decimals print(np.array([True, False]).dtype) print(np.array([1, 2, 3], dtype=np.int8).itemsize, "byte per item")
Output
[1. 2.5 3. ] [1. 2. 3.] float64 [1 2 3] bool 1 byte per item
Built-in Array Creation Functions
import numpy as np print(np.zeros(4)) print(np.ones((2, 3), dtype=int)) print(np.full((2, 2), 7)) print(np.arange(0, 10, 2)) # like range(), stop excluded print(np.linspace(0, 1, 5)) # 5 evenly spaced values, stop included print(np.eye(3, dtype=int)) # identity matrix
Output
[0. 0. 0. 0.] [[1 1 1] [1 1 1]] [[7 7] [7 7]] [0 2 4 6 8] [0. 0.25 0.5 0.75 1. ] [[1 0 0] [0 1 0] [0 0 1]]
Quick Statistics on Arrays
import numpy as np
marks = np.array([[78, 92, 65], [88, 70, 95]])
print("Total:", marks.sum())
print("Mean :", marks.mean())
print("Max :", marks.max())
print("Column sums:", marks.sum(axis=0)) # down each column
print("Row sums :", marks.sum(axis=1)) # across each rowOutput
Total: 488 Mean : 81.33333333333333 Max : 95 Column sums: [166 162 160] Row sums : [235 253]
axis=0 works down the rows (one result per column); axis=1 works across the columns (one result per row).
Key Takeaways
- An ndarray holds same-type values in compact memory and supports fast element-wise maths.
- ndim, shape, size and dtype describe an array; mixed numbers are upcast to float.
- zeros, ones, full, arange, linspace and eye create arrays quickly.
Video : Array Basics
Question / Answer (15 questions)
Answer : NumPy (Numerical Python) is the fundamental Python library for numerical and scientific computing. It provides the ndarray, a fast N-dimensional array of same-type values, plus mathematical functions that operate on whole arrays.
Answer : import numpy as np. The short alias np is a widely followed convention that keeps code concise and readable, e.g. np.array().
Answer : Arrays store same-type values in compact, continuous memory; they support vectorised element-wise operations executed in fast compiled code without Python loops; and they offer many built-in mathematical and statistical functions.
Answer : For a list, * repeats the list: [1, 2, 1, 2]. For an array, * multiplies each element: [2 4].
Answer : A 0-D array holds a single value and has no axes, e.g. np.array(42). Its ndim is 0 and its shape is ().
Answer : For a2 = np.array([[1,2,3,4,5,6],[11,22,33,44,55,66]]): ndim is 2 (two axes), shape is (2, 6) (2 rows, 6 columns) and size is 12 (total elements).
Answer : (2, 2, 3): two blocks, each with two rows of three elements. Its ndim is 3 and size is 12.
Answer : dtype is the data type shared by all elements. Because the list mixes ints and a float, NumPy upcasts all values to float64, giving [1. 2.5 3.].
Answer : Use astype(), e.g. np.array([1.7, 2.2]).astype(int) gives [1 2] – decimals are truncated. You can also set dtype when creating: np.array([1, 2], dtype=float).
Answer : np.arange(start, stop, step) uses a step size and excludes stop, like range(). np.linspace(start, stop, num) creates num evenly spaced values and includes stop by default.
Answer : np.zeros(shape) creates an array filled with 0 (float by default), np.ones(shape) one filled with 1, np.full(shape, value) one filled with a given value, and np.eye(n) an n × n identity matrix.
Answer : axis=0 operates down the rows, giving one result per column. axis=1 operates across the columns, giving one result per row.
Answer : sum(axis=0) gives column totals [166 162 160]; sum(axis=1) gives row totals [235 253].
Answer : itemsize is the number of bytes used by one element. An int8 array has itemsize 1 and a float64 array has itemsize 8.
Answer : pandas, SciPy, Matplotlib and scikit-learn.
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- NumPy Developers. (n.d.). NumPy: the absolute basics for beginners. NumPy User Guide. https://numpy.org/doc/stable/user/absolute_beginners.html
- NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
- NumPy Developers. (n.d.). Array creation. NumPy User Guide. https://numpy.org/doc/stable/user/basics.creation.html
- NumPy Developers. (n.d.). The N-dimensional array (ndarray). NumPy Reference. https://numpy.org/doc/stable/reference/arrays.ndarray.html
- Harris, C. R., Millman, K. J., van der Walt, S. J., et al. (2020). Array programming with NumPy. Nature, 585, 357–362. https://doi.org/10.1038/s41586-020-2649-2
- VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/