0
0
NumPydata~20 mins

Controlling copy behavior in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Copy Control Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this NumPy slicing and assignment?

Consider the following code snippet using NumPy arrays. What will be the output of print(a)?

NumPy
import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = a[1:4]
b[0] = 100
print(a)
A[ 1 100 3 4 5]
B[ 1 2 3 4 5]
C[100 100 100 4 5]
D[ 1 100 100 4 5]
Attempts:
2 left
💡 Hint

Remember that slicing a NumPy array returns a view, not a copy.

Predict Output
intermediate
2:00remaining
What does this code print when using np.copy()?

What will be printed after running this code?

NumPy
import numpy as np

a = np.array([10, 20, 30])
b = np.copy(a)
b[1] = 99
print(a)
A[99 20 30]
B[10 99 30]
C[10 20 99]
D[10 20 30]
Attempts:
2 left
💡 Hint

np.copy() creates a new array independent of the original.

data_output
advanced
2:00remaining
What is the shape of the array after this operation?

Given the following code, what is the shape of b?

NumPy
import numpy as np

a = np.arange(12).reshape(3,4)
b = a[:, 1:3].copy()
print(b.shape)
A(3, 3)
B(2, 3)
C(3, 2)
D(4, 2)
Attempts:
2 left
💡 Hint

Check the slicing dimensions before copying.

🔧 Debug
advanced
2:00remaining
Why does this code raise an error?

Examine the code below. Why does it raise an error?

NumPy
import numpy as np

a = np.array([1, 2, 3])
b = a[::2]
b[2] = 10
print(a)
AIndexError: assignment index out of range
BTypeError: 'numpy.ndarray' object is not callable
CNo error; prints [1 10 3]
DValueError: shape mismatch
Attempts:
2 left
💡 Hint

Check the length of the sliced array b.

🚀 Application
expert
2:00remaining
How to create an independent copy of a 2D NumPy array and modify it without affecting the original?

You have a 2D NumPy array a. You want to create a new array b that you can change freely without changing a. Which code snippet achieves this?

Ab = a[:, :]
Bb = a.copy()
Cb = np.array(a)
Db = a.view()
Attempts:
2 left
💡 Hint

Think about which method creates a deep copy.