-2
import numpy as np  
a = np.arange(20) 
print('a:', a) 
L1 = []
L1.append(a)
print('L1:', L1)
a[-8:17:1] =  1
print('a:', a)
L1.append(a)
print('L1:', L1) 

And output of above is -

a: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
L1: [array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])]
a: [ 0  1  2  3  4  5  6  7  8  9 10 11  1  1  1  1  1 17 18 19]
L1: [array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,  1,  1,  1,  1,  1,
       17, 18, 19]), array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,  1,  1,  1,  1,  1,
       17, 18, 19])]

Why is first element of L1 changing? And how to prevent it from changing?

1 Answers1

0

Variable a is not a simple data type (np.array), so when you assign or, in your case, append it to a variable, you are not appending a copy, but a reference to the object. Hence, any change on the object will be reflected everywhere it is referenced.

Using a.copy() should solve your problem:

L1.append(a.copy())