Why does
f = g = h = []
f.append(1)
make
f = [1], g=[1], h=[1]
?
Why are the lists linked like this? If I would have done the same with integer variables, they would not be linked.
Why does
f = g = h = []
f.append(1)
make
f = [1], g=[1], h=[1]
?
Why are the lists linked like this? If I would have done the same with integer variables, they would not be linked.
[]
creates a list at a particular location.
Then, you point f
at that location.
Then, you point g
at that location as well. And h
.
It follow naturally that, when you modify that list in-place (without changing its reference), everything pointed at it will see the change.
You say that changing an integer won't have this effect. That's because it's a different type of change. Integers in python are immutable, and cannot usually be changed in-place - rather, a new integer must be created (a new reference along with it) and then assigned to the name that was looking at the old one:
h = 5
id(h)
# 4318792464
h = 6
id(h)
# 4318792496
# note that these two addresses are different, meaning different locations.
if this means the old value is lost forever, then the garbage collector will eventually clean it up and free the memory it was occupying.
As you can see, modifying a list in-place doesn't change its reference:
f = g = []
id(f) == id(g)
# True
g.append(1)
id(f) == id(g)
# still True
g = [1] # make a new list at a different location, with the same value
f == g
# True
id(f) == id(g)
# False