'need explanation on why value assigned to a variable changes?

e=[[1,2,3],[4,5,6]]
f1=e
f2=e
f2[1][0]=e[1][0]+1
print(f2)
print(f1,e)

in this code, why value of f1 and e are changing by changing the value of an element in the array of f2? and why it is not happed in the case of assigning constant to e?



Solution 1:[1]

f1 and f2 are copys of e. Here is described how copy works. https://docs.python.org/3/library/copy.html

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

You can fix such behavior for example by using deepcopy

import copy
e=[[1,2,3],[4,5,6]]
f1=copy.deepcopy(e)
f2=copy.deepcopy(e)
f2[1][0]=e[1][0]+1
print(f2)
print(f1,e)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Janosch