Let's import the numpy
module.
import numpy as np
n = 10 # CHANGE ME
a1 = list(range(n))
a2 = np.arange(n)
if n <= 10:
print(a1)
print(a2)
%timeit [i**2 for i in a1]
%timeit a2**2
Numpy Arrays: much less flexible, but:
# (This cell contains a bunch of voodoo that
# helps with the graphics below. You don't need to
# know what this does.)
%load_ext gvmagic
from objgraph_helper import dot_refs
%dotstr dot_refs([a1])
%dotstr dot_refs([a2])
a2.strides
np.array([1,2,3])
linspace
np.linspace(-1, 1, 10)
zeros
np.zeros((10,10), np.float64)
These propagate to all elements:
a = np.array([1.2, 3, 4])
b = np.array([0.5, 0, 1])
Addition, multiplication, power, .. are all elementwise:
a+b
a*b
a**b
Matrix multiplication is np.dot(A, B)
for two 2D arrays.
Numpy arrays have two (most) important attributes:
a = np.random.rand(5, 4, 3)
a.shape
The .shape
attribute contains the dimensionality array as a tuple. So the tuple (5,4,3)
means that we're dealing with a three-dimensional array of size $5 \times 4 \times 3$.
(numpy.random.rand
just generates an array of random numbers of the given shape.)
a.dtype
Other dtype
s include np.complex64
, np.int32
, ...