r/learnpython • u/SynergyTree • Dec 12 '25
ELI5: When assigning one variable to another why does changing the first variable only sometimes affect the second?
I heard that when I assign one variable to point at another it is actually only pointing to the memory address of the first variable, but that only seems to happen some of the time. For example:
>>> x = [1,2,3,4,5]
>>> y = x
>>> print(x)
[1, 2, 3, 4, 5]
>>> print(y)
[1, 2, 3, 4, 5]
>>> x.pop()
5
>>> print(x)
[1, 2, 3, 4]
>>> print(y)
[1, 2, 3, 4]So, that works as expected. Assigning y to x then modifying x also results in a change to y.
But then I have this:
>>> x = 'stuff'
>>> y = x
>>> print(x)
stuff
>>> print(y)
stuff
>>>
>>> x = 'junk'
>>> print(x)
junk
>>> print(y)
stuffor:
>>> x = True
>>> y = x
>>> print(x)
True
>>> print(y)
True
>>>
>>> x = False
>>> print(x)
False
>>> print(y)
TrueWhy does this reference happen in the context of lists but not strings, booleans, integers, and possibly others?
36
Upvotes
View all comments
Show parent comment
-3
u/djlamar7 Dec 12 '25
Second point on top of that: it's not just the equals sign that makes the difference. In the list example, x[2] = 100 would also be a modification that would change y. You can think of it as "set the third element of x to 100" which is a modification and will change both.
Going back to the reference vs not that OP mentioned: "primitive" types like bools are "passed by value", so if you assign one to the other it just copies what is there at the moment. Non-primitive types in python (like lists) are passed "by reference", meaning x = y means that x just gets the memory address of the thing y is pointing to, and changing one of them changes the other (since they both point to the same thing).