Bird
Raised Fist0
TensorFlowml~20 mins

Indexing and slicing tensors in TensorFlow - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Tensor Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of slicing a 3D tensor
What is the output shape of the tensor after slicing in the code below?
TensorFlow
import tensorflow as tf

x = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
sliced = x[:, 1, :]
print(sliced.shape)
A(2, 1)
B(1, 1)
C(1, 2)
D(2, 2)
Attempts:
2 left
💡 Hint
Remember that ':' means selecting all elements along that axis.
Model Choice
intermediate
1:30remaining
Choosing correct slicing for extracting a column vector
Given a 2D tensor of shape (5, 4), which slicing extracts the third column as a 1D tensor?
Atensor[:, 2:3]
Btensor[2, :]
Ctensor[:, 2]
Dtensor[2]
Attempts:
2 left
💡 Hint
Remember that the first index is for rows and the second for columns.
Hyperparameter
advanced
1:30remaining
Effect of slicing on batch size in training data
If you have a tensor representing a batch of images with shape (64, 28, 28, 3), what is the shape after slicing with tensor[:32]?
A(64, 28, 28, 3)
B(32, 28, 28, 3)
C(32, 28, 28)
D(28, 28, 3)
Attempts:
2 left
💡 Hint
Slicing with :32 selects the first 32 elements along the first dimension.
🔧 Debug
advanced
1:30remaining
Identify the error in tensor slicing code
What error does the following code produce? import tensorflow as tf x = tf.constant([[1, 2, 3], [4, 5, 6]]) slice = x[:, 3] print(slice)
TensorFlow
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
slice = x[:, 3]
print(slice)
AIndexError: index 3 is out of bounds for axis 1 with size 3
BTypeError: unsupported operand type(s) for slicing
CValueError: cannot slice tensor with ':'
DNo error, prints a tensor
Attempts:
2 left
💡 Hint
Check the size of the second dimension and the index used.
🧠 Conceptual
expert
2:00remaining
Understanding advanced tensor slicing with steps
Given a 1D tensor x = tf.constant([10, 20, 30, 40, 50, 60]), what is the output of x[1:5:2].numpy()?
TensorFlow
import tensorflow as tf
x = tf.constant([10, 20, 30, 40, 50, 60])
result = x[1:5:2].numpy()
print(result)
A[20 40]
B[20 30 40 50]
C[30 50]
D[10 30 50]
Attempts:
2 left
💡 Hint
Remember slicing syntax: start:stop:step selects elements from start up to but not including stop, stepping by step.

Practice

(1/5)
1. What does indexing a tensor in TensorFlow do?
easy
A. Selects a single element by its position
B. Changes the shape of the tensor
C. Adds new elements to the tensor
D. Deletes elements from the tensor

Solution

  1. Step 1: Understand indexing

    Indexing means picking one element from a tensor by its position, like choosing one item from a list.
  2. Step 2: Compare with other options

    Changing shape, adding, or deleting elements are different operations, not indexing.
  3. Final Answer:

    Selects a single element by its position -> Option A
  4. Quick Check:

    Indexing = single element pick [OK]
Hint: Indexing picks one element, slicing picks many [OK]
Common Mistakes:
  • Thinking indexing changes tensor shape
  • Confusing indexing with adding elements
  • Assuming indexing deletes elements
2. Which of the following is the correct syntax to slice a 1D tensor t from index 2 to 5 (exclusive) in TensorFlow?
easy
A. t[2:5]
B. t.slice(2, 5)
C. t[2, 5]
D. t.slice(2:5)

Solution

  1. Step 1: Recall slicing syntax

    TensorFlow uses Python-style slicing: t[start:stop] to get elements from start up to but not including stop.
  2. Step 2: Check each option

    t[2:5] uses correct Python slice syntax. t.slice(2, 5) and D use incorrect method calls or syntax. t[2, 5] uses comma which is invalid for 1D slicing.
  3. Final Answer:

    t[2:5] -> Option A
  4. Quick Check:

    Slice syntax = t[start:stop] [OK]
Hint: Use square brackets with colon for slicing [OK]
Common Mistakes:
  • Using commas instead of colons in slices
  • Trying to call slice as a method incorrectly
  • Confusing slice stop index as inclusive
3. Given the tensor t = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), what is the output of t[1:, :2].numpy()?
medium
A. [[5 6] [8 9]]
B. [[1 2] [4 5]]
C. [[4 5 6] [7 8 9]]
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 first two columns gives [[4,5], [7,8]].
  3. Final Answer:

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

    Rows 1+ and cols 0-1 = [[4 5],[7 8]] [OK]
Hint: Remember slice stop is exclusive, so :2 means columns 0 and 1 [OK]
Common Mistakes:
  • Including column index 2 mistakenly
  • Starting rows from 0 instead of 1
  • Confusing rows and columns order
4. What is wrong with this TensorFlow slicing code?
t = tf.constant([10, 20, 30, 40, 50])
slice = t[1:6]
medium
A. Index 6 is out of range, causing an error
B. Slicing with stop index beyond length is allowed, no error
C. Syntax error due to missing colon
D. TensorFlow does not support slicing

Solution

  1. Step 1: Check slicing behavior with stop index

    In Python and TensorFlow, slicing stop index can be beyond tensor length without error; it stops at the end.
  2. Step 2: Analyze given code

    Tensor t has length 5, slicing 1:6 extracts elements from index 1 to end safely.
  3. Final Answer:

    Slicing with stop index beyond length is allowed, no error -> Option B
  4. Quick Check:

    Slice stop > length is safe [OK]
Hint: Slice stop can exceed length without error [OK]
Common Mistakes:
  • Expecting IndexError for slice stop beyond length
  • Confusing slicing with indexing single element
  • Thinking slicing syntax is invalid
5. You have a 3D tensor t = tf.constant([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]]). How do you extract the second element from each 2D matrix (i.e., elements 2, 4, 6, 8, 10, 12) using indexing and slicing?
hard
A. t[1, :, :]
B. t[:, 1, :]
C. t[:, :, 1]
D. t[:, 1]

Solution

  1. Step 1: Understand tensor shape and indexing

    The tensor shape is (3, 2, 2): 3 matrices, each 2x2. We want the second element in the last dimension (index 1).
  2. Step 2: Apply slicing to get second element in last dimension

    Using t[:, :, 1] selects all matrices (:), all rows (:), and the second element (index 1) in the last dimension.
  3. Final Answer:

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

    Last dim index 1 selects second elements [OK]
Hint: Use colon for all dims except last, index last dim 1 [OK]
Common Mistakes:
  • Mixing row and column indices
  • Using incomplete slicing like t[:, 1]
  • Selecting wrong dimension index