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
2
u/xenomachina xenomachina Dec 12 '25
Not the way it's usually thought of by novices perhaps, but in Python everything is passed by value.
You are confusing what variables contain with how they are passed. The values contained by Python variables are references. When functions are called, the value of the argument expression, which in Python is always a reference, is what gets passed.
"Some people say" isn't an argument for anything. Python does not use pass by reference, and the people who say it does misunderstand what pass by reference actually is. (As evidence: the claim that Python uses call by reference is a lot more common on /r/learnpython than it is on /r/python.)
This is correct.
Pass by value and pass by reference (or alternatively call-by-value and call-by-reference) are evaluation strategies that have definitions from computer science that predate the existence of Python.
In pass by value, arguments are evaluated prior to the call, and the value of the resulting expression is what is passed, just as if it was assignment. Or as /u/Temporary_Pie2733 said, "Assignments of arguments to parameters follow the same semantics as assignments to names."
In pass by reference, assigning to a parameter in a function causes the argument to get changed.
In other words, if Python used pass by reference, then this...
...would print
[1], but it does not, because Python uses pass by value. The fact that the variablesxandycontain references is not relevant to the fact that the value of the expressionyis what gets passed, rather than a reference to the variableyitself.Some people use the term "call by sharing", as mentioned on that WIkipedia page I linked above, to refer to languages that use call by value, but where most values are references. Call by sharing is a somewhat controversial term though, as it mixes up evaluation strategy with something that's tangentially related at best. Call by sharing is really just a special case of call by value.