I have used Python for a long time but I don't know how objects and the memory really work.
Until a few days ago, I thought that alpha = gamma
made a variable whose name was alpha
and saved in it a copy of gamma
, without linking the variables to each other. However, I have recently noticed that that doesn't happen. Both variables actually point to the same object. Nevertheless, the variables become independent when you change the data in one of them (depending on the variables).
There are many other cases in which variables don't behave like you would expect. This is an example I came upon:
>>> grid1=[[0]*4]*4
>>> grid2=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
>>> grid1 == grid2
True
>>> grid1[2][3]+=1
>>> grid2[2][3]+=1
>>> grid1
[[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
>>> grid2
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0]]
I have tried to find more information about how =
and other commands treat variables and found some threads, but I have many questions whose answer I don't know yet:
- Why did the behavior shown above with the lists take place?
- What should be done in order to avoid it (make
grid1
behave likegrid2
)? - Does this have anything to do with the modifiability of the variables? What does it really mean for a variable to be modifiable?
- When are variables the same object or different ones? How do you know if a command creates a separate variable or not (
x+=y
vsx = x + y
,append
vs+
)? - Is there an
==
which would have returnedfalse
in the example above (is
wouldn't work, those two variables were created in different steps and independently so they won't be in the same place in the memory) because ingrid1
all lists were in the same place in the memory while ingrid2
they were independent?
I haven't been able to find the answers to those questions anywhere, could anyone give a brief answer to the questions or provide a reference which explained these concepts? Thanks.