30 Mins

3. Array Creation Routines

Instantiating arrays with np.array

The np.array function is the primary method for creating NumPy arrays from existing Python structures like lists or tuples. It detects the data type automatically, though you can specify it using the dtype argument.

When you pass a list to np.array, NumPy creates a new ndarray object. If the input is a nested list, it will automatically create a multi-dimensional array.

It is crucial to ensure that the input structures have consistent dimensions, otherwise, you may result in an object array which lacks the performance benefits of standard NumPy types.

Operator Note: Always check the shape and dtype of your array after creation to ensure it matches your memory requirements.
Python 3
import numpy as np
# Create 1D array
arr_1d = np.array([1, 2, 3])
# Create 2D array
arr_2d = np.array([[1, 2], [3, 4]], dtype='float32')
print(arr_1d, arr_2d.dtype)

Preallocating memory: np.zeros, np.ones, np.full, and np.empty

Preallocation is an optimization technique where you allocate memory for an array before filling it. This avoids repeated memory reallocations during loop operations.

np.zeros initializes elements to 0, np.ones to 1, and np.full allows you to specify a custom fill value.

np.empty is the fastest method, as it allocates memory without initializing values. The contents will be whatever arbitrary data happened to be in that memory location, making it very dangerous if not overwritten immediately.

FunctionInitial Value
np.zeros0.0
np.ones1.0
np.fullFill Value
np.emptyUninitialized/Random
Operator Note: Use np.empty for high-performance scenarios where you guarantee that every index will be populated shortly after creation.
Python 3
import numpy as np
print(np.zeros((2, 2)))
print(np.full((2, 2), 7))
print(np.empty((1, 2)))

Identity and unit diagonal creation

In linear algebra, the identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. NumPy provides np.identity and np.eye for this purpose.

np.identity creates a square identity matrix. np.eye is more flexible; it can create non-square arrays and allows you to specify the index of the diagonal (k=0 for main, positive for upper, negative for lower).

These routines are foundational for matrix inversion and solving systems of linear equations.

Operator Note: If you need an identity matrix that is not square, use np.eye.
Python 3
import numpy as np
identity = np.identity(3)
eye_matrix = np.eye(3, 4, k=1)
print('Identity:\n', identity)
print('Eye with offset:\n', eye_matrix)

Working with existing arrays

Often you need a new array with the same shape and data type as an existing one. Instead of manually inspecting the attributes, you can use _like variants.

np.zeros_like, np.ones_like, and np.full_like accept an existing array as an input and output a new array of the same shape and type, populated with the target values.

These functions are essential for writing generic code that works regardless of the input data shape.

Operator Note: Using _like functions preserves the metadata of the original array, including dtype and memory layout.
Python 3
import numpy as np
base = np.array([[1, 2], [3, 4]])
new_arr = np.zeros_like(base)
print(new_arr)

Knowledge Check

Ready to test your understanding of 3. Array Creation Routines?

Back