I have a list x
which contains another list object
as below:
x = [ [1, 0] ]
Now, I am performing the concatenation operation on the list x
a = x x
a[0][0] = 100
print(a)
Output:
[[100, 0], [100, 0]]
Here, I have not updated value of a[1][0]
but it is still modified. What is causing this?
CodePudding user response:
Use copy.deepcopy()
from copy import deepcopy
x = [[1, 0]]
a = deepcopy(x) deepcopy(x)
a[0][0] = 100
Example
print(a)
Output
[[100, 0], [1, 0]]
CodePudding user response:
This is because both elements of a
are pointing to the same element x
. Try this very simple example:
x = [1,2]
y = x
y[0] = 10
print(x)
Surprisingly, the outcome is [10,2]
. You can avoid this behavior using copy
, which breaks this relationship and creates a new object.
a=x x
a[0]=a[0].copy()
a[0][0]=100
Would do the job.
CodePudding user response:
Another way to do this to create a copy is:
x = [ [1, 0] ]
a = [x[:],x[:]]
a[0][0] = 100
print(a)
You can create a new copy to the list instead of reference with x[:]
.
Output:
[[100], [[1, 0]]]
CodePudding user response:
because a after concatenation is [x,x]
a[0]
is accessing x
which is a variable.
and a[0][0]
is implying to change x[0]
, thus
changing overall x
, achieving [x[0],x[0]]
.
Try to initialize a as [[1,0],[1,0]]
and run the
same command, you'll see that it'll have your desired
output or x x.copy()
[edit]
this code:
x = [5]
y = x.copy()
x[0] = 1
print(x)
print(y)
outputs:
[6]
[5]