NumPy Arrays: Create, Index, Slice, and Reshape
Imagine you have a spreadsheet with a million rows of numbers and you need to multiply every single value by 2. With a regular Python list, you'd write a loop that visits each cell one by one. It works, but it's slow.
NumPy gives you a supercharged list called an ndarray (short for N-dimensional array). Instead of looping through items one at a time, NumPy processes the entire batch in a single operation - often 50 to 100 times faster than plain Python.
In this tutorial, you'll learn how to create NumPy arrays, access individual elements, slice out sections, reshape arrays into different dimensions, and understand the key properties that make arrays different from lists.
Why Should You Use NumPy Instead of Lists?
A NumPy array requires every element to be the same type (all integers, or all floats). This constraint lets NumPy store data in a tight, continuous block of memory and perform operations in compiled C code under the hood.
# Doubling each number with a loop
numbers = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in numbers]
print(doubled) # [2, 4, 6, 8, 10]import numpy as np
numbers = np.array([1, 2, 3, 4, 5])
doubled = numbers * 2
print(doubled) # [ 2 4 6 8 10]How Do You Create a NumPy Array?
The most common way is np.array(), which converts a Python list (or list of lists) into a NumPy array. But NumPy also has handy shortcut functions for common patterns.
What Are dtype, shape, and ndim?
Every NumPy array carries metadata about itself. The three most important properties are dtype (data type of each element), shape (dimensions), and ndim (number of dimensions).
How Do You Index and Slice NumPy Arrays?
Indexing and slicing work almost identically to Python lists. You use square brackets with zero-based indexes. Negative indexes count from the end.
For 2D arrays (matrices), you separate row and column indexes with a comma. This is cleaner than the nested bracket syntax you'd use with lists of lists.
How Do You Reshape an Array?
Reshaping changes the arrangement of elements without changing the data itself. Think of it like rearranging 12 books from one long shelf into a 3-by-4 grid. The books are the same - only the layout changes.
Practice Exercises
Create a NumPy array called temps containing the values 72.1, 68.5, 75.3, 80.0, 77.8 (daily temperatures). Print the array, its dtype, and its shape on separate lines.
import numpy as np # Create the temps array # Print the array, dtype, and shape
Create three arrays and print each one:
1. z - an array of 6 zeros
2. o - a 2x3 array of ones
3. r - numbers from 5 to 25 (inclusive) in steps of 5 using arange
Print each array on its own line.
import numpy as np # Create the three arrays # Print each one
Given the array data = np.array([100, 200, 300, 400, 500, 600]), print:
1. The first element
2. The last element (use negative indexing)
3. The element at index 3
import numpy as np data = np.array([100, 200, 300, 400, 500, 600]) # Print the three elements
Given arr = np.arange(10, 100, 10) (which is [10, 20, 30, 40, 50, 60, 70, 80, 90]), print:
1. The first three elements
2. The last four elements
3. Every other element starting from the second (index 1)
import numpy as np arr = np.arange(10, 100, 10) # Print the three slices
What does the following code print? Think about the shape before and after reshape.
import numpy as np
a = np.arange(1, 13)
b = a.reshape(3, -1)
print(b.shape)
print(b[1, 2])import numpy as np a = np.arange(1, 13) b = a.reshape(3, -1) print(b.shape) print(b[1, 2])
Create a 4x4 matrix of numbers 1 through 16 using arange and reshape. Then print:
1. The entire second row
2. The entire third column
3. The 2x2 submatrix from the bottom-right corner
import numpy as np # Create 4x4 matrix (1 to 16) # Print second row, third column, bottom-right 2x2
This code tries to create a 3x5 grid of numbers but crashes with an error. Fix the bug so it prints a 3x5 array.
import numpy as np # BUG: This crashes! data = np.arange(1, 16) grid = data.reshape(3, 5) print(grid)