Worksheets › Class 11 › Introduction to NumPy › Cheat sheet
Class 11 Introduction to NumPy: cheat sheet
CBSE Informatics Practices. NumPy arrays: creating them from lists and with zeros, ones and arange; their attributes ndim, shape, size, dtype and itemsize; and element-wise arithmetic.
Key ideas
- NumPy (Numerical Python) is imported as np; an array holds items of a single data type, stored next to each other in memory.
- np.array() turns a list into a 1-D array, and a list of equal-length lists into a 2-D array of rows and columns.
- One float in the list makes every item a float and one string makes every item a string; dtype=float forces floats.
- ndim gives the number of dimensions, shape the length along each, such as (3, 4), and size the total number of elements.
- np.zeros((r, c)) and np.ones((r, c)) fill an array with 0s or 1s, float64 by default; np.arange(a, b, s) works like range and stops before b.
- itemsize is the bytes one element takes (8 for float64, 4 for int32), so the elements take size × itemsize bytes in all.
- Arithmetic on an array works on every element: an array * 2 doubles each item, while a list * 2 repeats the list.
Remember
| Shape | 2-D: (rows, columns); 1-D: (n,) with a comma |
| size | rows × columns: np.zeros((3, 4)).size → 12 |
| dtype from the items | all whole numbers → int; any float → float; any string → string |
| itemsize | float64 = 8 bytes; int32 = 32 bits = 4 bytes |
| Total bytes | size × itemsize: np.ones((3, 5), dtype=np.int32) → 15 × 4 = 60 |
| arange | np.arange(1, 10, 2) → 1, 3, 5, 7, 9; np.arange(6) → 0 to 5 |
| Array and list | import numpy as np L = [2, 5, 7] A = np.array(L) print(L * 2) # [2, 5, 7, 2, 5, 7] print(A * 2) # [ 4 10 14] |
Watch out
- Writing shape as (columns, rows): it is (rows, columns).
- Counting the stop value in arange: np.arange(0, 10, 2) ends at 8.
- Taking zeros() items as whole numbers: they are float64, 8 bytes each.
- Thinking an array with one string still holds numbers: every item becomes text.
Worked example
What are the elements of c? Write them separated by commas. import numpy as np a = np.array([24, 13, 17, 45]) b = np.array([32, 30, 33, 28]) c = a + b
Working: element by element: 24 + 32, 13 + 30, 17 + 33, 45 + 28
Answer: 56, 43, 50, 73
Practise Introduction to NumPy
Revise with this page, then practise: every Introduction to NumPy sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.