Bird
0
0

You have a large numpy array arr of size 1 million elements. You want to add 10 to each element efficiently. Which approach is best?

hard📝 Application Q8 of 15
NumPy - Array Operations
You have a large numpy array arr of size 1 million elements. You want to add 10 to each element efficiently. Which approach is best?
AUse <code>arr += 10</code> to modify in-place
BConvert to list, add 10, then convert back
CUse a for-loop to add 10 to each element
DUse <code>arr = arr + 10</code> to create a new array
Step-by-Step Solution
Solution:
  1. Step 1: Compare memory usage of methods

    Creating a new array duplicates memory, costly for large arrays.
  2. Step 2: Identify in-place operation benefits

    Using '+=' modifies original array without extra memory.
  3. Step 3: Evaluate other methods

    For-loop and list conversion are slower and less efficient.
  4. Final Answer:

    Use arr += 10 to modify in-place -> Option A
  5. Quick Check:

    In-place '+=' is best for large array efficiency [OK]
Quick Trick: Use '+=' for large arrays to save memory and time [OK]
Common Mistakes:
  • Using '+' creates new array
  • Using slow loops
  • Converting to lists wastes memory

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes