runtime

compare approaches one problem · three ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

NumPy slices: views vs copiesbehaves differently

Take the first three readings, change one, and look at the original array.

what differs

A basic NumPy slice shares memory with its array, so writing to it writes to the original. .copy() makes independent data. Python list slices are always copies, which is why the habit from lists is wrong for NumPy.

at a glance

approachuse it when
A · slice (a view)You want a window into the data without copying it (and you know changes show through).
B · slice().copy()You'll change the piece and the original must stay as it was.
C · Python list sliceFor comparison: list slicing always copies.

Watch out: Fancy indexing (readings[[0, 1, 2]]) and boolean masks return copies. np.shares_memory(a, b) tells you which you have.

the outputs

Each approach runs on the same input.

concepts

viewscopiesshared memory

learn it

Indexing, slicing and masks

related comparisons

Assignment vs shallow copy vs deepcopy · Chained assignment vs .loc

A · slice (a view)
B · slice().copy()
C · Python list slice
Compare Python Approaches · Runtime