Bird
0
0

Identify the error in this code snippet that tries to add 10 to each element of arr in-place:

medium📝 Debug Q14 of 15
NumPy - Array Operations
Identify the error in this code snippet that tries to add 10 to each element of arr in-place:
import numpy as np
arr = np.array([4, 5, 6])
arr = arr.add(10)
print(arr)
AAll of the above.
BThe operation <code>arr = arr.add(10)</code> creates a new array, not in-place.
CThe correct in-place addition uses <code>arr += 10</code>.
DThe method <code>add</code> does not exist for numpy arrays.
Step-by-Step Solution
Solution:
  1. Step 1: Check if numpy arrays have add() method

    NumPy arrays do not have an add method; this causes an AttributeError.
  2. Step 2: Understand in-place addition syntax

    Using arr = arr.add(10) is invalid and does not perform in-place addition; correct syntax is arr += 10.
  3. Step 3: Combine observations

    All points are true: method doesn't exist, code creates new array if it did, and correct syntax is arr += 10.
  4. Final Answer:

    All of the above. -> Option A
  5. Quick Check:

    Use arr += 10; no arr.add() method [OK]
Quick Trick: No arr.add(); use arr += 10 for in-place add [OK]
Common Mistakes:
  • Trying to use arr.add() method
  • Assigning arr = arr + 10 expecting in-place
  • Ignoring AttributeError from invalid method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes