Python Arrays
Python has no "array" keyword. When tutorials say "array" they almost always mean list. There are arrays in two libraries — useful when you need raw performance or n-dimensional math.
The default: list
PYTHON
nums = [10, 20, 30, 40] nums.append(50) print(sum(nums), max(nums), min(nums))
Lists hold values of any type, in any order, and resize automatically. Pick a list unless you have a reason not to.
The standard-library array
array.array is a typed, single-type-only sequence — slightly faster and uses less memory than a list:
PYTHON
from array import array
nums = array('i', [10, 20, 30]) # 'i' = signed int
nums.append(40)
print(nums)
NumPy — the n-dimensional one
For real numeric work — vectors, matrices, science, ML — use NumPy:
PYTHON
# pip install numpy import numpy as np a = np.array([1, 2, 3, 4]) print(a * 2) # element-wise print(a.mean(), a.sum()) m = np.array([[1, 2], [3, 4]]) print(m @ m) # matrix multiply
Which to use
| Need | Pick |
|---|---|
| General-purpose, mixed types | list |
| Compact typed buffer | array.array |
| Numeric computing, vectors, matrices | numpy.ndarray |
| O(1) appends/pops from both ends | collections.deque |
Tip: If your "array" is going to be looped over and processed numerically, switching to NumPy makes the same code 10–100× faster. The change is usually a few imports.
Example
Example
# Use list — true "arrays" come from the array or numpy modules. nums = [10, 20, 30, 40] nums.append(50) print(sum(nums), max(nums), min(nums))Try it Yourself »
Exercise
For numeric vectors/matrices, the standard library is…
import
as np
Five letters.
Discussion
Loading…