Q: why does this happen with lists in python 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]


A: Because objects a and b reference the same object (as you have observed by checking both objects' ids). 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.


A: By calling b = a, you're actually just assigning another name to the same object, as id(a) and id(b) show. If you want to copy a to b you should use either b = a[:] or b = list(a). In that case, a and b will have separate lifecycles. Try calling id() and check.
