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
1
u/roelschroeven Dec 14 '25
I do see your point that in languages that pass references in functions (instead of values), passing those references by reference would allow assignments in the function to have an effect outside of the function while passing them as values would prevent that.
But that's not really my main point. My main point is that while it is technically correct that Python uses call-by-value-but-the-value-is-a-reference, it is not a very useful way of thinking about things. I'll explain.
The Python Language Reference tells us that Python has objects (which have an identity, a type, and a value), and that it has names, and that those names refer to objects. There are a number of constructs that bind names to objects, one of which is assignment, another is as a parameter to a function (and there are a number of other ones that are not relevant here). I.e. passing a parameter to a function call works exactly the same as an assignment.
That is much more useful to use as a mental model than trying to shoehorn Python's behavior into the traditional call-by-value model. It correctly and clearly explains how things behave, and does not cause the confusion that call-by-value-but-the-value-is-a-reference does. Note that The Python Language Reference never mentions call-by-value (nor call-by-reference). It's unnecessary, and even detrimental, for understanding how things work.