NumPy Tutorial menu

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 listNumPy array
Item typesCan mix any typesAll items the same type
Speed for mathsSlowVery fast
Maths on all itemsNeeds a loopOne expression
MemoryMoreLess

Look at the difference:

Example

python
marks = [70, 85, 90]
print(marks * 2)
Output
[70, 85, 90, 70, 85, 90]

Example

python
import numpy as np

marks = np.array([70, 85, 90])
print(marks * 2)
Output
[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

bash
pip install numpy

If 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

python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output
[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

python
import numpy as np
print(np.__version__)
Output
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

python
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")
Output
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?

Learn NumPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp