0
0
PyTorchml~10 mins

Indexing and slicing in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select the first row of the tensor.

PyTorch
import torch
x = torch.tensor([[1, 2], [3, 4], [5, 6]])
first_row = x[1]
Drag options to blanks, or click blank then click option'
A[0]
B[1]
C[:, 0]
D[0, :]
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 instead of 0 to get the first row.
Using slicing syntax instead of indexing.
2fill in blank
medium

Complete the code to select the last column of the tensor.

PyTorch
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
last_col = x[1]
Drag options to blanks, or click blank then click option'
A[0, -1]
B[-1, :]
C[:, -1]
D[:, 0]
Attempts:
3 left
💡 Hint
Common Mistakes
Using row index -1 instead of column index -1.
Swapping row and column indices.
3fill in blank
hard

Fix the error in the code to correctly slice the tensor to get rows 1 and 2.

PyTorch
import torch
x = torch.tensor([[10, 20], [30, 40], [50, 60]])
subset = x[1]
Drag options to blanks, or click blank then click option'
A[1:2]
B[1, 3]
C[1;3]
D[1:3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a comma instead of colon in slicing.
Using incorrect stop index.
4fill in blank
hard

Fill both blanks to select the middle column and rows 0 and 1.

PyTorch
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
subset = x[1][2]
Drag options to blanks, or click blank then click option'
A[0:2]
B[1]
C[:, 1]
D[1:3]
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping row and column indices.
Using incorrect slice ranges.
5fill in blank
hard

Fill all three blanks to create a tensor slice with rows 1 to 2 and columns 0 to 1.

PyTorch
import torch
x = torch.tensor([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
subset = x[1][2][3]
Drag options to blanks, or click blank then click option'
A[1:3]
B[:, 0:2]
C[0:2]
D[:, 1:3]
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up row and column slices.
Using incorrect slice indices.