np.array and np.asarray
What it is
np.array(obj) builds a new array from a nested sequence and copies by default. np.asarray(obj) returns the input unchanged if it is already a compatible array, and only copies otherwise.
Why it matters
asarray is the right first line of a function that accepts 'array-like' input: it normalises lists into arrays without paying for a copy when the caller already handed you an array.
In the real world: Turning a list of today's product prices from an API into an array so discounts and taxes can be applied to all of them at once.
def standardize(x):
x = np.asarray(x, dtype=float) # no copy if already a float array
return (x - x.mean(axis=0)) / x.std(axis=0)
np.array([[1, 2], [3, 4]], dtype='float32')Using asarray and then writing into the result. If the caller passed an array, you have just mutated theirs. Use np.array(x, dtype=float) (or np.asarray(x).copy()) when you intend to write.
Practise it: Pad Sequences to a Fixed Length