Challenge - 5 Problems
In-place Operations Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of in-place addition with NumPy arrays
What is the output of the following code snippet?
NumPy
import numpy as np arr = np.array([1, 2, 3]) arr += 5 print(arr)
Attempts:
2 left
💡 Hint
Remember that '+=' modifies the array in place by adding 5 to each element.
✗ Incorrect
The '+=' operator adds 5 to each element of the array in place, changing the original array to [6, 7, 8].
❓ data_output
intermediate2:00remaining
Memory usage difference between in-place and out-of-place operations
Given the code below, which option correctly describes the memory usage behavior?
NumPy
import numpy as np arr = np.ones((1000, 1000)) arr2 = arr * 2 # Out-of-place arr *= 2 # In-place
Attempts:
2 left
💡 Hint
Multiplying with '*' creates a new array; '*=' modifies the existing array.
✗ Incorrect
arr2 = arr * 2 creates a new array, using extra memory. arr *= 2 modifies arr in place, saving memory.
🔧 Debug
advanced2:00remaining
Identify the error in in-place operation
What error will this code raise and why?
NumPy
import numpy as np arr = np.array([1, 2, 3], dtype=int) arr += 2.5
Attempts:
2 left
💡 Hint
Check if the operation tries to store floats into an integer array.
✗ Incorrect
NumPy does not allow in-place addition of floats to an integer array without explicit casting, causing a TypeError.
🚀 Application
advanced2:00remaining
Using in-place operations to optimize a data transformation
You have a large NumPy array 'data' and want to normalize it by subtracting the mean and dividing by the standard deviation. Which code snippet uses in-place operations correctly to save memory?
Attempts:
2 left
💡 Hint
Look for use of '-=' and '/=' operators to modify 'data' in place.
✗ Incorrect
Using '-=' and '/=' modifies the original array without creating new arrays, saving memory.
🧠 Conceptual
expert2:00remaining
Why prefer in-place operations in large data processing?
Which is the best reason to prefer in-place operations when working with large NumPy arrays?
Attempts:
2 left
💡 Hint
Think about memory and temporary data when processing large arrays.
✗ Incorrect
In-place operations save memory by modifying data directly, avoiding extra copies.