Why NumPy over lists
A Python list can hold anything but is slow at maths; a NumPy array holds one kind of number and does maths on everything at once.
In this page:
Why NumPy over lists
Python lists store pointers to full Python objects, so arithmetic needs a slow loop. NumPy arrays store raw numbers in one contiguous block of memory and apply operations in compiled code. That means less memory, faster maths and much shorter code.
Note:
Multiplying a list by 2 repeats it; multiplying an array by 2 doubles every element.
Example: Why NumPy over lists
import numpy as np
nums = [1, 2, 3]
arr = np.array(nums)
print("list * 2 :", nums * 2)
print("array * 2 :", arr * 2)
print("list + list:", nums + nums)
print("array + array:", arr + arr)
# Output:
# list * 2 : [1, 2, 3, 1, 2, 3]
# array * 2 : [2 4 6]
# list + list: [1, 2, 3, 1, 2, 3]
# array + array: [2 4 6]
Related Topics
Common Mistakes
- Expecting list * 2 to double the values
- Mixing types and being surprised by automatic conversion
- Using lists for large numeric datasets
Chapter Summary
- Arrays use contiguous typed memory
- Operators work element-wise on arrays
- Arrays use far less memory than lists
- Code is shorter with no explicit loops
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: