NumPy Introduction
NumPy is the main Python library for fast work with arrays of numbers.
What is NumPy?
- NumPy stands for Numerical Python
- It gives Python a powerful array object called
ndarray(n-dimensional array) - It was created in 2005 by Travis Oliphant and is free and open source
- Most of NumPy is written in C, which is why it is so fast
Why Not Just Use Lists?
Python lists are flexible, but they are slow for maths on many numbers. A NumPy array stores all its values in one block of memory, all of the same type. This lets the computer process them very quickly.
| Python list | NumPy array | |
|---|---|---|
| Item types | Can mix any types | All items the same type |
| Speed for maths | Slow | Very fast |
| Maths on all items | Needs a loop | One expression |
| Memory | More | Less |
Look at the difference:
Example
marks = [70, 85, 90]
print(marks * 2)[70, 85, 90, 70, 85, 90]
Example
import numpy as np
marks = np.array([70, 85, 90])
print(marks * 2)[140 170 180]
With a list, * 2 repeats the list. With an array, * 2 multiplies every number.
Installing NumPy
If you have Python and pip, install NumPy from the terminal:
Example
pip install numpyIf you use Anaconda or Google Colab, NumPy is already installed. You can skip this step.
Importing NumPy
Import it in your program with the short name np. Everyone uses this name, so you will see it in every tutorial and project.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))[1 2 3 4 5] <class 'numpy.ndarray'>
Notice that an array prints without commas, which helps you tell it apart from a list.
Checking the Version
Example
import numpy as np
print(np.__version__)2.1.3
Your version number may be different. Any version 1.20 or newer works for this tutorial.
A Quick Speed Test
Here we add one to a million numbers, first with a list and then with NumPy:
Example
import time
import numpy as np
nums = list(range(1_000_000))
start = time.time()
result = [n + 1 for n in nums]
print("List:", round(time.time() - start, 4), "seconds")
arr = np.arange(1_000_000)
start = time.time()
result = arr + 1
print("NumPy:", round(time.time() - start, 4), "seconds")List: 0.0412 seconds NumPy: 0.0012 seconds
The exact times depend on your computer, but NumPy is usually many times faster.
Exercise
Exercise
What does np.array([1, 2, 3]) * 3 give?
