the full guide

Arrays in Python

Python has three array-like options. A list can hold any mix of types. The array module's array holds one simple type compactly. A NumPy array holds one type, and supports fast maths on the whole array.

5 min Intermediate

What you need: The earlier topics of this module.

Definition

Python has three array-like options. A list can hold any mix of types. The array module's array holds one simple type compactly. A NumPy array holds one type, and supports fast maths on the whole array.

In simple words

A list is a bag that holds anything. An array is a tray of identical slots. A NumPy array is that tray with a built-in calculator.

Why it matters

Choosing correctly affects speed a lot. For numbers in AI work, the answer is almost always NumPy.

How it works

OptionMixed types?Fast maths?Use for
listYesNoGeneral work
array.arrayNoNoSaving memory, rarely
numpy.arrayNoYesNumbers, data, AI

In code

arrays.py
import array
import numpy as np

mixed = [1, "two", 3.0]
numbers = array.array("i", [1, 2, 3])
fast = np.array([1, 2, 3])

print(mixed)
print(numbers.tolist())
print("List * 2:", [1, 2, 3] * 2)
print("NumPy * 2:", fast * 2)

Output

[1, 'two', 3.0]
[1, 2, 3]
List * 2: [1, 2, 3, 1, 2, 3]
NumPy * 2: [2 4 6]

Common mistakes

  • Expecting a list * 2 to double each number. It repeats the list.
  • Looping over a NumPy array when a whole-array operation would do it.

Check yourself

Question 1

1. What is [1, 2] * 2?

Question 2

2. Which should you use for maths on a million numbers?

Summary

  • Lists are flexible, and NumPy arrays are fast for numbers.
  • The array module is rarely needed.

Finished reading?

Sources: The Python Tutorial, python.org