Sub topic 2
Creating arrays
This chapter assumes you know basic Python (lists, loops, functions) and can run code in a script or notebook. It also assumes you have met the ndarray as a typed, fixed-size block of data. Later chapters cover shape, dtype conversion, and indexing in depth. Here the focus is how each creation routine decides the shape, the dtype, and whether data is copied.
The working model
Every creation routine answers three questions:
- Shape: how many elements are there along each axis?
- Dtype: what type is every element?
- Values: where do the values come from? They may be copied from existing data, computed from a rule, or left uninitialized.
Most beginner errors come from guessing one of these wrongly. The routines fall into four families.
| Family | Functions | Values come from |
|---|---|---|
| Conversion | `np.array`, `np.asarray` | Existing Python data or arrays |
| Constant fill | `np.zeros`, `np.ones`, `np.full`, `np.empty`, `np.eye` | A fixed rule or nothing |
| Sequences | `np.arange`, `np.linspace` | An arithmetic progression |
| Shape-matching | `np.zeros_like`, `np.ones_like`, `np.full_like`, `np.empty_like` | Same as the fill family, with shape and dtype taken from another array |
Converting existing data with np.array
np.array takes nested sequences and builds an array. The nesting depth sets the number of dimensions. NumPy picks the smallest dtype that holds every element, so one float makes the whole array float, and one string makes it a string array.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2.5, 3])
c = np.array([1, "x"])
print(a.dtype, b.dtype) # int64 float64
print(c.dtype) # a string dtype such as <U21The string result in the last case is a common surprise. The number 1 becomes the text "1". NumPy does not raise an error, so check dtype whenever input data is mixed.
Pass dtype= to choose the type yourself instead of relying on inference:
import numpy as np
print(np.array([1, 2, 3], dtype=np.float32)) # [1. 2. 3.]
print(np.array([0, 1, 2], dtype=bool)) # [False True True]Ragged input
Every row must have the same length. Modern NumPy rejects ragged nested lists instead of quietly building an array of lists.
import numpy as np
try:
np.array([[1, 2], [3]])
except ValueError as err:
print("ValueError:", err)
r = np.array([[1, 2], [3]], dtype=object)
print(r.shape) # (2,)With dtype=object you get a 1-D array of Python lists. It stores pointers and loses the speed benefits of a typed array, so use it only when you really need ragged data.
array versus asarray
np.array copies its input by default. np.asarray returns the input itself when it is already an ndarray of the requested dtype, and converts only when it has to.
import numpy as np
x = np.arange(3)
y = np.asarray(x)
z = np.array(x)
print(y is x) # True: no copy was made
print(z is x) # False: np.array copied
y[0] = 100
print(x) # [100 1 2]
z[1] = -1
print(x) # [100 1 2]Use np.asarray at the start of a function that accepts lists or arrays and should not duplicate large inputs. Use np.array when you want an independent copy.
Constant fills
These routines take a shape and, optionally, a dtype. The shape is a single tuple. A very common error is passing the dimensions as separate arguments.
import numpy as np
z = np.zeros((2, 3))
o = np.ones((2, 3), dtype=np.int32)
f = np.full((2, 2), 7)
e = np.eye(3)
print(z.dtype, o.dtype, f.dtype) # float64 int32 int64
print(e.shape) # (3, 3)
try:
np.zeros(2, 3)
except TypeError as err:
print("TypeError:", err)np.zeros(2, 3) fails because the second positional argument is dtype, and 3 is not a dtype. The correct call is np.zeros((2, 3)). For a 1-D array, a plain integer works: np.zeros(5).
Note the defaults. zeros, ones, empty, and eye produce float64 unless you say otherwise. np.full infers the dtype from the fill value, so np.full((2, 2), 7) is an integer array and np.full((2, 2), 7.0) is a float array.
np.eye(n) builds an identity matrix. It also takes k to shift the diagonal, for example np.eye(3, k=1).
np.empty is not zeros
np.empty allocates memory and does not write to it. The array holds whatever bytes were there before, which may look like zeros, garbage, or leftovers from earlier arrays.
Sequences: arange and linspace
np.arange(start, stop, step) mirrors Python's range: the start is included and the stop is excluded. It accepts floats.
np.linspace(start, stop, num) returns exactly num points, and the stop is included by default.
import numpy as np
print(np.arange(5)) # [0 1 2 3 4]
print(np.arange(1, 10, 3)) # [1 4 7]
print(np.arange(0, 1, 0.25)) # [0. 0.25 0.5 0.75]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
print(np.linspace(0, 1, 4, endpoint=False)) # [0. 0.25 0.5 0.75]The two functions differ in what you specify. With arange you give the step, and the length follows from it. With linspace you give the length, and the step follows from it.
With float steps, arange can be unreliable. Binary floating point cannot represent a step such as 0.1 exactly. The computed length is ceil((stop - start) / step), so a rounding error can add or drop the last element. When you care about the count or the endpoint, use linspace. Use arange with integer steps.
Shape-matching: the _like functions
np.zeros_like(a), np.ones_like(a), np.empty_like(a), and np.full_like(a, value) copy the shape and dtype of a. This is useful when you need an output buffer that matches an input.
import numpy as np
a = np.array([[1, 2], [3, 4]])
t = np.zeros_like(a)
u = np.full_like(a, 9)
v = np.full_like(a, 0.5)
w = np.full_like(a, 0.5, dtype=float)
print(t.dtype, t.shape) # int64 (2, 2)
print(v) # [[0 0]
# [0 0]]
print(w) # [[0.5 0.5]
# [0.5 0.5]]The array v is the trap. Because a is an integer array, full_like keeps the integer dtype and casts 0.5 to 0. Pass dtype= whenever the fill value does not fit the source dtype.
Common errors, summarized
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: Cannot interpret '3' as a data type` | Dimensions passed as separate arguments | Pass one tuple: `np.zeros((2, 3))` |
| `ValueError` about an inhomogeneous shape | Ragged nested lists | Make rows equal length, or use `dtype=object` on purpose |
| Numbers turned into strings | One string in the input | Clean the input or set `dtype=` |
| Floats silently became integers | `*_like` or `full` kept an integer dtype | Pass `dtype=float` |
| Wrong number of elements from `arange` | Float step rounding | Use `np.linspace` |
| Changes leak into the original | `np.asarray` returned the same object | Use `np.array` or `.copy()` |
| Random-looking values | Read from `np.empty` before writing | Use `np.zeros`, or fill first |
Exercise
You write grid = np.full_like(np.array([1, 2, 3]), 2.5) and expect [2.5 2.5 2.5]. What do you get, why, and how do you fix it?
Show answer
You get [2 2 2]. np.full_like keeps the dtype of its first argument, which is an integer dtype, so the fill value 2.5 is cast to an integer and truncated. Fix it by passing a dtype: np.full_like(np.array([1, 2, 3]), 2.5, dtype=float), which returns [2.5 2.5 2.5].
Exercise
You need 11 evenly spaced values from 0 to 1, inclusive of both ends. Which function is the safer choice, and what call do you write?
Show answer
Use np.linspace(0, 1, 11). It takes the number of points and includes the stop value by default, so the count and endpoint are exact. np.arange(0, 1.1, 0.1) depends on floating-point rounding and may give a different number of elements.