Bird
0
0

Given a 2D numpy array arr with shape (3, 3), which of the following expressions will extract the diagonal elements as a 1D array?

hard📝 Application Q9 of 15
NumPy - Indexing and Slicing
Given a 2D numpy array arr with shape (3, 3), which of the following expressions will extract the diagonal elements as a 1D array?
Aarr[range(3), range(3)]
Barr[:, 0]
Carr[0, :]
Darr[1, 1]
Step-by-Step Solution
Solution:
  1. Step 1: Understand diagonal extraction

    Diagonal elements have equal row and column indices: (0,0), (1,1), (2,2).
  2. Step 2: Use indexing with matching row and column indices

    arr[range(3), range(3)] selects elements at (0,0), (1,1), (2,2).
  3. Final Answer:

    arr[range(3), range(3)] -> Option A
  4. Quick Check:

    Matching row and column indices extract diagonal [OK]
Quick Trick: Use arr[range(n), range(n)] to get diagonal elements [OK]
Common Mistakes:
  • Selecting entire row or column
  • Using single element indexing
  • Confusing slicing with indexing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes