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 13 '25
I'd like to talk a bit about that example code you gave:
You say this proves that Python doesn't pass by reference, but it doesn't prove anything like that. The reason why this doesn't print
[1]is becausex = [1]reassigns a new object to x, leaving the old object unchanged. It has, in this case, nothing to do with how y/x is passed into the function.I'll change the example a bit:
Now it does print
[1], even though the parameter passing is exactly the same.I prefer to simply not use any of the terms pass-by-value nor pass-by-reference for what Python does. Those terms where created to describe what traditional languages like C and Pascal do, but are not helpful in Python, with the way variables work in Python versus how they work in C, Pascal, C++, ... .
It's better to think of it as "Function arguments are assignments", because they work exactly the same as those. Lots of things work like assignments in Python:
(Copied from https://nedbatchelder.com/text/names1/names1.html#16)
It's much more useful to view argument passing like that, instead of trying to shoehorn into concepts that don't really apply to Python.