When I assign one list to another, I see that upon changing one of the elements in one list, the other element is automatically assigned with that value.
What is the reason for this behavior?
>>> a = [1,2,3] # create a list
>>> b = a
>>> b
[1, 2, 3]
>>> id(a)
40307408
>>> id(b)
40307408
>>> a[2] = 5
>>> b
[1, 2, 5]
>>> b[1] = 10
>>> a
[1, 10, 5]
Because objects a
and b
reference the same object (as you have observed by checking both objects' id
s). If you change a value in one, the other will change as well. It's like b
is a clone of a
, but will continue being a clone.
To avoid this behaviour, you can do:
b = a[:]
Which assigns b
a copy of a
.
Or:
b = list(a)
Or:
import copy
b = copy.copy(a) # The copy module can be useful for nested lists.