Why NumPy Is Faster

Why are NumPy arrays faster than Python lists?

Answer

NumPy arrays are faster because they use vectorized operations, which perform optimized C code instead of Python loops.

These operations are usually elementwise, such as for +, -, *, and / but they need not be. We also have a simple "vectorized syntax" for these operations, as shown below (the same logic applies to +, -, etc.):

Vectorized NumPy version:

Python
import numpy as np

arr = np.arange(1_000_000)
result = arr * 2

Python loop version (much slower):

Python
lst = list(range(1_000_000))
result = [x * 2 for x in lst]
Back to collection