Bird
Raised Fist0
PyTorchml~20 mins

Indexing and slicing in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Indexing and Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of slicing a 2D tensor
What is the output of the following PyTorch code snippet?
PyTorch
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = x[1:, :2]
print(result)
Atensor([[4, 5], [7, 8]])
Btensor([[5, 6], [8, 9]])
Ctensor([[1, 2], [4, 5]])
Dtensor([[2, 3], [5, 6]])
Attempts:
2 left
💡 Hint
Remember that x[1:, :2] means rows from index 1 to end, columns from index 0 up to but not including 2.
❓ Model Choice
intermediate
1:30remaining
Choosing correct indexing for batch selection
You have a tensor `data` of shape (10, 3, 28, 28) representing 10 images with 3 color channels and 28x28 pixels. Which indexing expression correctly selects the first 5 images?
Adata[5:]
Bdata[:5]
Cdata[:, :5]
Ddata[0:5, 1]
Attempts:
2 left
💡 Hint
The first dimension is the batch size (number of images).
❓ Metrics
advanced
1:30remaining
Effect of slicing on tensor shape
Given a tensor `t` of shape (8, 16, 32), what is the shape of `t[:, 4:10, 5:15]`?
A(8, 6, 10)
B(8, 6, 9)
C(8, 5, 10)
D(8, 7, 10)
Attempts:
2 left
💡 Hint
Subtract start index from end index for each sliced dimension.
🔧 Debug
advanced
1:30remaining
Identify the error in tensor indexing
What error does the following PyTorch code raise?
PyTorch
import torch
t = torch.randn(4, 5)
result = t[1:3, 5]
ANo error, returns a tensor
BTypeError: only integers, slices (`:`), ellipsis (`...`), None and long or byte Variables are valid indices
CValueError: too many indices for tensor of dimension 2
DIndexError: index 5 is out of bounds for dimension 1 with size 5
Attempts:
2 left
💡 Hint
Check the size of dimension 1 and the index used.
🧠 Conceptual
expert
2:30remaining
Understanding advanced slicing with steps
Given a tensor `x` of shape (12,), what is the output of `x[10:2:-3]`?
PyTorch
import torch
x = torch.arange(12)
result = x[10:2:-3]
print(result)
Atensor([10, 7, 1])
Btensor([10, 8, 5])
Ctensor([10, 7, 4])
Dtensor([10, 7, 3])
Attempts:
2 left
💡 Hint
Remember slicing with negative step goes backward, start index included, stop index excluded.

Practice

(1/5)
1. What does the expression tensor[2] do in PyTorch when tensor is a 1D tensor?
easy
A. Selects every second element starting at index 2
B. Selects elements from index 0 to 2
C. Selects the element at index 2
D. Raises an error because indexing starts at 1

Solution

  1. Step 1: Understand 1D tensor indexing

    In PyTorch, indexing a 1D tensor with [2] picks the element at position 2 (0-based index).
  2. Step 2: Confirm indexing behavior

    Since indexing starts at 0, tensor[2] returns the third element.
  3. Final Answer:

    Selects the element at index 2 -> Option C
  4. Quick Check:

    Indexing with a single integer picks one element [OK]
Hint: Single index picks one element by position [OK]
Common Mistakes:
  • Thinking indexing starts at 1
  • Confusing slicing with indexing
  • Expecting a range instead of one element
2. Which of the following is the correct syntax to slice a 1D tensor t to get elements from index 1 to 4 (excluding 4)?
easy
A. t(1:4)
B. t[1:4]
C. t[1-4]
D. t[1,4]

Solution

  1. Step 1: Recall slicing syntax

    Slicing uses start:stop inside square brackets to select elements from start index up to but not including stop index.
  2. Step 2: Check each option

    t[1:4] uses correct slicing syntax t[1:4]. Options A, B, and C use invalid syntax for slicing.
  3. Final Answer:

    t[1:4] -> Option B
  4. Quick Check:

    Slicing uses colon inside brackets [OK]
Hint: Use colon inside brackets for slicing [OK]
Common Mistakes:
  • Using comma instead of colon for slicing
  • Using parentheses instead of brackets
  • Using minus sign instead of colon
3. Given the tensor t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), what is the output of t[1:, :2]?
medium
A. [[5, 6], [8, 9]]
B. [[2, 3], [5, 6]]
C. [[1, 2], [4, 5]]
D. [[4, 5], [7, 8]]

Solution

  1. Step 1: Understand slicing t[1:, :2]

    1: means rows from index 1 to end (rows 1 and 2). :2 means columns from start to index 2 (columns 0 and 1).
  2. Step 2: Extract the sliced elements

    Rows 1 and 2 are [[4,5,6],[7,8,9]]. Taking columns 0 and 1 gives [[4,5],[7,8]].
  3. Final Answer:

    [[4, 5], [7, 8]] -> Option D
  4. Quick Check:

    Row slice 1: and col slice :2 gives [[4,5],[7,8]] [OK]
Hint: Rows after 1, columns before 2 slice tensor [OK]
Common Mistakes:
  • Mixing row and column indices
  • Including column index 2 mistakenly
  • Confusing slicing ranges
4. What is wrong with this code snippet?
import torch
t = torch.tensor([1, 2, 3, 4, 5])
print(t[::2, 1])
medium
A. Trying to index 2D on a 1D tensor
B. Slicing syntax is incorrect
C. Tensor is not created properly
D. Print statement missing parentheses

Solution

  1. Step 1: Analyze tensor shape

    The tensor t is 1D with shape (5,). It has only one dimension.
  2. Step 2: Check indexing used

    The code uses t[::2, 1] which tries to index two dimensions (rows and columns). This causes an error because t is 1D.
  3. Final Answer:

    Trying to index 2D on a 1D tensor -> Option A
  4. Quick Check:

    1D tensor cannot be indexed with two indices [OK]
Hint: Match number of indices to tensor dimensions [OK]
Common Mistakes:
  • Assuming 1D tensor can be indexed like 2D
  • Confusing slicing syntax with indexing
  • Ignoring tensor shape before indexing
5. You have a 3D tensor t with shape (4, 5, 6). Which indexing expression extracts all elements from the second dimension at index 3, across all batches and features?
hard
A. t[:, 3, :]
B. t[3, :, :]
C. t[:, :, 3]
D. t[3, 3, :]

Solution

  1. Step 1: Understand tensor dimensions

    Tensor shape is (4, 5, 6): first dim = batches, second dim = 5 elements, third dim = 6 features.
  2. Step 2: Select all batches, index 3 in second dim, all features

    Use : to select all in first and third dims, and 3 to select index 3 in second dim, so t[:, 3, :].
  3. Final Answer:

    t[:, 3, :] -> Option A
  4. Quick Check:

    Colon means all, index 3 picks second dim element [OK]
Hint: Use colon for all dims, index for specific dim [OK]
Common Mistakes:
  • Mixing dimension order
  • Using wrong index for dimension
  • Using single index for multiple dims
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard