Explore Library
Code Quiz

Reshape View Mutates Caller's Array

A NumPy function accidentally corrupts its input because reshape returns a view, not a copy.

Codepython
import numpy as np

def clip_and_double(a):
    # flatten, clip negatives to 0, then return doubled values
    b = a.reshape(-1)
    b[b < 0] = 0
    return b * 2

x = np.array([[1, -2], [-3, 4]])
result = clip_and_double(x)
print(result)      # [2 0 0 8]
print(x)           # caller expects [[1, -2], [-3, 4]] ... but it changed!

What is the bug in this function?