There are many ways to create NumPy arrays: from Python lists, or with functions that build arrays of zeros, ones, ranges or evenly spaced values.
What You Will Learn
- np.array() for 1D, 2D and 3D arrays
- zeros, ones, full, eye
- arange and linspace
- Creating arrays like another array
Prerequisites
From a List
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3], [4, 5, 6]])
c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(a.ndim, b.ndim, c.ndim)
print(b)
Explanation: Each extra level of brackets adds a dimension. A 2D array is like a table with rows and columns.
1 2 3 [[1 2 3] [4 5 6]]
Zeros, Ones and Full
print(np.zeros(3))
print(np.ones((2, 3), dtype=int))
print(np.full((2, 2), 7))
Explanation: The shape is a tuple: (rows, columns). zeros and ones are floats by default.
[0. 0. 0.] [[1 1 1] [1 1 1]] [[7 7] [7 7]]
Identity Matrix
print(np.eye(3))
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
arange
print(np.arange(5))
print(np.arange(2, 10, 2))
print(np.arange(0, 1, 0.25))
Explanation: Like Python’s range(), the stop value is excluded, but arange also accepts decimal steps.
[0 1 2 3 4] [2 4 6 8] [0. 0.25 0.5 0.75]
linspace
print(np.linspace(0, 1, 5))
Explanation: linspace(start, stop, num) gives exactly num evenly spaced values, including stop. It is commonly used to draw smooth graphs.
[0. 0.25 0.5 0.75 1. ]
empty and like-functions
a = np.array([[1, 2], [3, 4]])
print(np.zeros_like(a))
print(np.ones_like(a))
[[0 0] [0 0]] [[1 1] [1 1]]
np.empty(shape) does not set values, so it contains leftover memory. Use it only if you will fill every element.Choosing the Function
| Function | Use when |
|---|---|
| np.array(list) | You already have data |
| np.zeros / np.ones / np.full | You need a placeholder of fixed shape |
| np.arange | Steps of a fixed size |
| np.linspace | A fixed number of points |
| np.eye | Identity matrix |
Common Errors
| Problem | Cause and fix |
|---|---|
| Array has dtype=object or a warning about ragged sequences | Your nested lists have different lengths. Every row must be the same length. |
TypeError with np.zeros(2, 3) |
Pass the shape as a tuple: np.zeros((2, 3)). |
Practice Exercises
- Create a 5×5 array of all 9s.
- Create 10 values evenly spaced from 0 to 2π.
- Create the even numbers from 10 to 50.
Interview Questions
Q: arange vs linspace?
arange uses a step and excludes stop; linspace uses a count and includes stop.
Summary
Use np.array for existing data, zeros/ones/full/eye for fixed shapes, and arange or linspace for sequences.
Next: NumPy Data Types · Inspect an Array
Machine Learning Tutorials, Courses and Certifications