-1

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.

caesar
  • 185
  • 4
  • they *are* linked when you do it with anything and everything (in the first style of writing it) – Paritosh Singh Feb 09 '20 at 14:22
  • That' because `f`,`g`,`h` point to `[]`. When you mutate any of the variables in-place then changes are reflected in all of the variables. And `int` is **immutable** datatype. So, once you mutate the value it points to different object. – Ch3steR Feb 09 '20 at 14:24
  • Read https://nedbatchelder.com/text/names.html – chepner Feb 09 '20 at 14:40
  • 1
    You can't mutate integer values. `f.append(1)` and `f = 2` are two *completely* different operations. – chepner Feb 09 '20 at 14:42

1 Answers1

3

[] 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
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • 2
    This is as much a FAQ as anything. See the "Answer Well-Asked Questions" section of https://stackoverflow.com/help/how-to-answer, particularly the bullet point regarding questions that "have been asked and answered many times before". – Charles Duffy Feb 09 '20 at 14:41
  • You got the order wrong, `f` gets assigned first, not `h`. – Kelly Bundy Feb 09 '20 at 15:09