Python: List is overwritten. But Why?

arrays, list, numpy, python

Solution

NumPy array slicing and Python list slicing work differently. Slicing on Python lists returns a shallow copy of the list, while on NumPy arrays it simply returns a view of the array items.

From NumPy docs:

Note that slices of arrays do not copy the internal array data but also produce new views of the original data.

So, in your first solution you can use `.copy` to get a copy of the array:

signal_exp_new.append(signal_exp[0].copy())

Problem

The following code: ``` file_path = 'some_path/data.txt' exp = loadtxt(file_path) signal_exp = [] signal_exp.append(exp[1, :]) signal_exp_new = [] signal_exp_new.append(signal_exp[0]) signal_exp_new[0][0:800] = 0.0 ``` will result in `signal_exp` beeing overwritten at the first 800 elements as well as `signal_exp_new`. I found the solution but I do not understand why the next one works as expected (of me at least): ``` file_path = 'some_path/data.txt' exp = loadtxt(file_path) signal_exp = [] signal_exp.append(exp[0, :].tolist()) signal_exp_new = [] signal_exp_new.append(signal_exp[0][:]) for l in range(800): signal_exp_new[0][l] = 0.0 ``` Can anyone give me an explanation why in the latter case, the original list is not overwritten but in the first case it is?

Original source