Array Slicing and Indexing
Select individual elements, rows, columns, and sub-arrays using integer and slice notation on multi-dimensional arrays.
Array Slicing and Indexing is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Integer Indexing in 1-D Arrays
A 1-D array is indexed just like a list: a[0] is first, a[-1] is last. Indexing returns a single scalar, and negative numbers count from the end.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10
print(a[-1]) # 50
print(a[2]) # 30Slicing 1-D Arrays
Slices use start:stop:step like lists, but a NumPy slice returns a view — no copy. Change the slice and you change the original, so use .copy() when needed.
import numpy as np
a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(a[2:7]) # [2 3 4 5 6]
print(a[::2]) # [0 2 4 6 8]
print(a[::-1]) # [9 8 7 6 5 4 3 2 1 0]Indexing 2-D Arrays
For 2-D arrays, use comma syntax: a[row, col]. A lone colon means everything along that axis, so a[0, :] grabs a whole row and a[:, 1] a whole column.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(m[1, 2]) # 6 (row 1, col 2)
print(m[0, :]) # [1 2 3] first row
print(m[:, 1]) # [2 5 8] second column2-D Array Slicing
Give two slices to grab a rectangular block: a[0:2, 1:3] takes those rows and columns. The result is a view, so edits flow back to the original.
import numpy as np
m = np.arange(16).reshape(4, 4)
print(m)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(m[1:3, 1:3])
# [[ 5 6]
# [ 9 10]]Boolean Indexing
Pass a boolean array to keep only the elements marked True. This boolean indexing always returns a copy and is the standard way to filter data.
import numpy as np
a = np.array([3, 7, 2, 9, 1, 6])
mask = a > 4
print(mask) # [False True False True False True]
print(a[mask]) # [7 9 6]
# Equivalent one-liner
print(a[a > 4]) # [7 9 6]Fancy Indexing with Integer Arrays
Fancy indexing lets you pick elements at any positions with a list of integers — in any order, even repeating them. It always returns a copy.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
idx = [4, 1, 3]
print(a[idx]) # [50 20 40]
# Selecting specific rows from a 2D array
m = np.arange(20).reshape(4, 5)
print(m[[0, 2], :]) # rows 0 and 2np.where for Conditional Selection
np.where(condition, x, y) picks from x where the condition is True and from y where it's False — a fast, loop-free way to choose values per element.
import numpy as np
a = np.array([5, -3, 8, -1, 2])
result = np.where(a > 0, a, 0) # keep positives, zero negatives
print(result) # [5 0 8 0 2]
# np.where with one argument returns indices of True elements
idx = np.where(a > 0)
print(idx) # (array([0, 2, 4]),)Slices Are Views — Gotcha!
Heads up: since slices are views, editing one edits the original array too. Need an independent piece? Call .copy() on the slice first. ⚠️
import numpy as np
original = np.arange(6)
view = original[2:5] # view, not copy
view[:] = 99
print(original) # [ 0 1 99 99 99 5] -- original changed!
safe = original[2:5].copy() # true copy
safe[:] = 0
print(original) # [ 0 1 99 99 99 5] -- unchanged3-D Array Indexing
Arrays can have any number of dimensions. For a 3-D array you index with three positions: a[depth, row, col] — common when handling batches of images.
import numpy as np
t = np.arange(24).reshape(2, 3, 4)
print(t.shape) # (2, 3, 4)
print(t[0, :, :]) # first 'plane' -- shape (3, 4)
print(t[1, 2, 3]) # scalar at depth 1, row 2, col 3Assigning Values Through Indexing
Any indexing form works on the left side of an = to change values in place — slices, masks, or fancy indices. Assign a scalar and NumPy spreads it to every spot.
import numpy as np
a = np.zeros(8)
a[2:5] = 1.0 # slice assignment
print(a) # [0. 0. 1. 1. 1. 0. 0. 0.]
a[a == 0] = -1.0 # boolean assignment
print(a) # [-1. -1. 1. 1. 1. -1. -1. -1.]Ellipsis and np.newaxis
np.newaxis (or None) adds a size-1 axis, turning a (5,) array into a (5, 1) column vector — a common setup before broadcasting.
import numpy as np
t = np.ones((2, 3, 4))
print(t[..., 0].shape) # (2, 3) -- last axis fixed at 0
a = np.array([1, 2, 3])
print(a.shape) # (3,)
print(a[:, np.newaxis].shape) # (3, 1) column vectorQuick Check
Test your understanding of NumPy array slicing and indexing from this lesson.
Lesson Recap
Well done! Slices are views that share memory, boolean indexing filters and copies, and fancy indexing grabs any elements you name. Next: universal functions.
Frequently asked questions
Is the “Array Slicing and Indexing” lesson free?
Yes — the full text of “Array Slicing and Indexing” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Array Slicing and Indexing”?
Select individual elements, rows, columns, and sub-arrays using integer and slice notation on multi-dimensional arrays. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Array Slicing and Indexing” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating NumPy Arrays
- Array Attributes and Inspection
- Element-Wise Arithmetic
- Array Slicing and Indexing