Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 17 of 25

NumPy arrays

NumPy, short for Numerical Python, is the library that nearly every scientific and machine-learning tool in Python is built on, including pandas, scikit-learn, TensorFlow and PyTorch. Its central object is the array, or ndarray: a grid of values that all share one type.

By convention NumPy is imported under the short name np.

import numpy as np

marks = np.array([72, 85, 90, 64])
print(marks)          # [72 85 90 64]

An array prints without commas. That is the quickest way to tell an array from a list on screen.

Why not just use a list? Arithmetic on an array applies to every element at once, which is called vectorisation. With a list, * 2 repeats the list. With an array it doubles every value, and no loop is needed. In a full Python installation this also runs far faster, because NumPy does the work in compiled code.

nums = [1, 2, 3]
print(nums * 2)            # [1, 2, 3, 1, 2, 3]
print(np.array(nums) * 2)  # [2 4 6]

Every array describes itself through a few attributes:

  • a.shape is the size along each dimension, for example (4,) or (2, 3)
  • a.ndim is the number of dimensions
  • a.size is the total number of elements
  • a.dtype is the element type, such as int64, float64 or bool

A two-dimensional array is built from a list of rows, all of the same length. Its shape is written as (rows, columns).

m = np.array([[1, 2, 3],
              [4, 5, 6]])
print(m.shape)   # (2, 3)
print(m.ndim)    # 2

Because all elements share one type, mixing whole numbers and decimals makes every element a float64. Floats print with a trailing dot, so 2. means 2.0.

This app runs a teaching version of NumPy inside your browser. It covers everything in these lessons and prints results the way NumPy does, so the same code works in a full Python installation. Two differences to know: random numbers will not match real NumPy's, and slicing here always makes a copy (see the indexing topic).

Key takeaways

  • A NumPy array holds numbers of one type and does maths on every element at once: a * 2 doubles each value.
  • shape is the size along each dimension, ndim the number of dimensions, size the total number of elements and dtype the element type.
  • Adding two arrays adds matching elements. It does not join them the way + joins lists.
  • Start with import numpy as np.

Common mistakes

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.