Introduction to NumPy
NumPy and arrays
Say why an array is faster than a list.
NumPy ('Numerical Python') is a Python package for data analysis and scientific computing. It provides a powerful n-dimensional array object and tools for working with it. Install it with pip install numpy, and use it with import numpy as np (np is a short alias).
What an array is. An array stores many values under one name.
- Every element has the same data type.
- Each element has an index; the first is at index 0, the second at 1, and so on: zero-based indexing, as with lists.
- The whole array is stored contiguously (side by side) in memory, which makes operations fast.
- NumPy's array class is officially ndarray, usually just called an array.
Lists versus arrays:
- A list can mix types, like [1, 3.4, 'hello', 'a@']; an array holds one type only, like an array of floats.
- List elements may be scattered in memory; array elements are contiguous.
- A list cannot do arithmetic on every element at once; an array can: if A1 is an array, A1/3 divides each element by 3 (element-wise operation). Trying the same on a list gives an error.
- Arrays take less memory, because the type is not stored with every element.
Example (new): prices = np.array([120, 80, 45]) can be given a 10 per cent discount in one step, prices * 0.9, giving [108.0, 72.0, 40.5]; with an ordinary list you would need a loop to change each price.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.