← Back to Python Course | Chapter 13: Data Science & Web | Lesson 2 of 14

Python NumPy Arrays

Creating Arrays with Functions

NumPy provides dedicated constructor functions instead of building arrays from Python lists by hand: np.zeros(shape) and np.ones(shape) create arrays pre-filled with a constant, while np.arange() and np.linspace() generate evenly spaced numeric ranges directly as arrays.

Example: Creating Arrays with Functions

python
import numpy as np
print(np.zeros(3))
print(np.arange(0, 10, 2))

Slicing and Indexing

Indexing and slicing a NumPy array follows the same array[start:stop:step] syntax as a Python list, but extends naturally to multiple dimensions with comma-separated indices like array[row, col]. Slices of NumPy arrays are *views* onto the original data by default, not independent copies, so modifying a slice can modify the source array too.

Example: Slicing and Indexing

python
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr[0, 1])
print(arr[:, 0])

Reshaping and Resizing

.reshape() changes how an array's existing data is organized into dimensions -- turning a flat 12-element array into a 3x4 grid, for instance -- without copying or altering any of the underlying values, as long as the new shape's total element count matches the original.

Example: Reshaping and Resizing

python
import numpy as np
arr = np.arange(12)
print(arr.reshape(3, 4))

Array Stacking and Splitting

np.concatenate() (or the more specific np.vstack()/np.hstack()) joins multiple arrays together along a chosen axis, while np.split() divides one array into several smaller ones. These are the array equivalents of combining or breaking apart lists, but operating on whole numeric blocks at once.

Example: Array Stacking and Splitting

python
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(np.concatenate([a, b]))

Conditional Selection

Boolean indexing lets you select array elements using a condition directly, like array[array > 10], which builds a boolean mask and returns only the elements where that mask is True. This replaces manual filtering loops with a single expressive line that NumPy executes at compiled speed.

Example: Conditional Selection

python
import numpy as np
arr = np.array([5, 15, 25])
print(arr[arr > 10])

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.