Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List is overwritten. But Why?

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?

like image 726
DaPhil Avatar asked Jul 19 '26 12:07

DaPhil


1 Answers

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())
like image 65
Ashwini Chaudhary Avatar answered Jul 22 '26 03:07

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!