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
| Option | Mixed types? | Fast maths? | Use for |
|---|---|---|---|
| list | Yes | No | General work |
| array.array | No | No | Saving memory, rarely |
| numpy.array | No | Yes | Numbers, data, AI |
In code
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
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