Creating Arrays and dtypes

Where an array comes from, and the type it settles on.

Several ways in

From a list, from a range, or filled. arange and linspace are the two that come up constantly: one steps, the other divides an interval evenly.

import numpy as np

print(np.array([1, 2, 3]))
print(np.arange(0, 10, 2))
print(np.zeros(3))
print(np.linspace(0, 1, 5))

The dtype is chosen for you, until it is not

One float in a list of ints makes the whole array float, because everything has to share a type. Being explicit is how you stop that surprising you later.

import numpy as np

print(np.array([1, 2, 3]).dtype)
print(np.array([1, 2, 3.0]).dtype)
print(np.array([1, 2, 3], dtype=float))

Exercise

Try It Yourself

Write even_numbers(stop) that returns a numpy array of the even numbers from 0 up to but not including stop.

Press Run to see output

Check Your Understanding