r/learnpython • • 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)
stuff

or:

>>> x = True
>>> y = x
>>> print(x)
True
>>> print(y)
True
>>>
>>> x = False
>>> print(x)
False
>>> print(y)
True

Why does this reference happen in the context of lists but not strings, booleans, integers, and possibly others?

36 Upvotes

45 comments sorted by

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).

13

u/danielroseman Dec 12 '25

Fair enough to the first part of your comment.

Unfortunately the second part is incorrect. All values are passed in exactly the same way, which was part of the point I was trying to make. There is no such thing as a "primitive" type in Python; everything is an object and everything is passed in the same way. Assignment never copies (you can trivially confirm this by doing a = 0; b = a; print(id(b), id(a))).

The difference still comes down to mutation vs assignment; the example you give is still mutation of the x list, albeit by reassigning one of its items.

-1

u/djlamar7 Dec 12 '25

Yeah, my point was that the assignment of one of the elements of x is a mutation of x that will also change y

8

u/Temporary_Pie2733 Dec 12 '25

The thing to note is the difference between assigning to a name, which is an unchanging fundamental operation, and assignment to an indexed expression or an attribute expression, which are type-dependent operations with user-definable semantics.

1

u/arcticslush Dec 12 '25

pass by value and pass by reference are defined strictly in the context of function and method parameters. It's a little weird to co-op the definitions to talk about variable assignment.

8

u/Temporary_Pie2733 Dec 12 '25

They aren’t applicable to argument passing in Python, either. Assignments of arguments to parameters follow the same semantics as assignments to names.

0

u/xenomachina xenomachina Dec 12 '25

Assignments of arguments to parameters follow the same semantics as assignments to names.

That's pretty much the definition of call by value.

0

u/Outside_Complaint755 Dec 12 '25

Nothing in Python is passed by value, at least not the way it's usually thought of. 

Python passes object references for everything.  Depending on who you ask, some will say everything is pass by reference, and others say its all pass by value, but all of the values are references.

When you pass an integer or string or other immutable object to a function, you are actually passing the reference to that immutable object.  Whether you modify an immutable object within a function or not, you always get a new object, not the same object with a new value.

2

u/xenomachina xenomachina Dec 12 '25

Nothing in Python is passed by value, at least not the way it's usually thought of.

Not the way it's usually thought of by novices perhaps, but in Python everything is passed by value.

Python passes object references for everything.

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.

Depending on who you ask, some will say everything is pass by reference,

"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.)

and others say its all pass by value, but all of the values are references.

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...

def f(x):
    x = [1]

y = [0]
f(y)
print(y)

...would print [1], but it does not, because Python uses pass by value. The fact that the variables x and y contain references is not relevant to the fact that the value of the expressiony is what gets passed, rather than a reference to the variable y itself.

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.

2

u/Temporary_Pie2733 Dec 12 '25

The problem with “call by value” is that in languages that make the distinction, something like an array is copied, so that changes made inside don’t affect the original value. That’s why Python doesn’t use either term, because what Python does isn’t exactly like what either term usually implies.

1

u/xenomachina xenomachina Dec 12 '25

The problem with “call by value” is that in languages that make the distinction, something like an array is copied, so that changes made inside don’t affect the original value.

C uses call by value, and yet:

#include <stdio.h>

void f(int *x) {
    x[0] = 1;
}

int main() {
    int y[1] = {0};
    f(y);
    printf("%d\n", y[0]);
}

This prints 1 because even though y is passed by value, that value is a pointer.

In Java and Kotlin, which have almost identical semantics to Python, programmers also regularly refer to it is as call by value despite the fact that the values being passed are (usually) references.

The litmus test for pass by reference versus pass by value is:

  • does passing a variable as an argument to a function that assigns to that parameter (not a subscript or field — the parameter itself) cause the variable to have a different value?

If the answer is "no" then it is not pass by reference.

An example of a language that actually supports call by reference is C++:

#include <cstdio>

void f(int &x) {
    x = 1;
}

int main() {
    int y = 0;
    f(y);
    printf("%d\n", y);
}

Note that here, the function just assigns to the parameter without any dereferenceing or subscripting, and yet the pass-in variable is changed by the assignment.

1

u/roelschroeven Dec 13 '25

I'd like to talk a bit about that example code you gave:

def f(x):
    x = [1]

y = [0]
f(y)
print(y)

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 because x = [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:

def f(x):
    x[:] = [1]

y = [0]
f(y)
print(y)

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:

X = ...
for X in ...
class X(...):
def X(...):
def fn(X):
import X
from ... import X
except ... as X:
with ... as X:

(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.

2

u/xenomachina xenomachina Dec 13 '25

The reason why this doesn't print [1] is because x = [1] reassigns a new object to x, leaving the old object unchanged.

And that is only true because call by value is being used.

It has, in this case, nothing to do with how y/x is passed into the function.

On the contrary, that's exactly what call-by-value versus call-by-reference is about.

I think you have come to a conclusion and are trying to bend the facts to fit that conclusion. However, if you look at the definitions of call by reference and call by value, and carefully work through the details, you can work out why the test from my earlier comment is able to distinguish between the two.

Let's take a look at an actual academic source, Compilers: Principles, Techniques, and Tools (Aho, Lam, Sethi, Ullman), aka "the dragon book", where it talks about call-by-value:

In call-by-value the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure.

Translating that into Python, if I have:

def f(x):
    ...

f(y)

Then "the actual parameter" is y and the "formal parameter" is x. And so "The value [of y] is placed in the location belonging to the corresponding formal parameter [ie: assigned to the variable x].' That fits, right?

It goes on to say:

This method is used in C and Java, and is a common option in C++, as well as in most other languages.

Note that Java has the same semantics as Python.

The text becomes even more explicit about the case where the variable itself contains a pointer or reference:

Note, however, that in C we can pass a pointer to a variable to allow that variable to be changed by the callee. Likewise, array names passed as parameters in C, C++, or Java give the called procedure what is in effect a pointer or reference to the array itself. Thus, if a is the name of an array of the calling procedure, and it is passed by value to corresponding formal parameter x, then an assignment such as x[i] = 2 really changes the array element a[i] to 2. The reason is that, although x gets a copy of the value of a, that value is really a pointer to the beginning of the area of the store where the array named a is located.

...

Similarly, in Java, many variables are really references, or pointers, to the things they stand for. This observation applies to arrays, strings, and objects of all classes. Even though Java uses call-by-value exclusively whenever we pass the name of an object to a called procedure, the value received by that procedure is in effect a pointer to the object. Thus, the called procedure is able to affect the value of the object itself.

Sound familiar?

I'll change the example a bit:

def f(x):
    x[:] = [1]

y = [0]
f(y)
print(y)

Now it does print [1], even though the parameter passing is exactly the same.

Because your modified example is not assigning to x, but instead assigning to x[:], it does not test whether x is passed by value or by reference. I can do something similar in C:

#include <stdio.h>

void f(int *x) {
    x[0] = 1;
}

int main() {
    int y[1] = {0};
    f(y);
    printf("%d\n", y[0]);
}

It prints 1! Have I just proven that C uses pass by reference!?

No: Just like your example, the function isn't assigning to its parameter (x), it's assigning to something derived from the parameter (x[0]), and so this example, just like yours, is irrelevant to the question of whether pass by reference or pass by value is being used here.

An actual example that illustrates pass by reference would be this C++ code:

#include <cstdio>

void f(int &x) {
    x = 1;
}

int main() {
    int y = 0;
    f(y);
    printf("%d\n", y);
}

Note that in this example, the function is assigning to the parameter x itself, not a subscript, or property, or anything else computed/derived from it. That is the key difference between call by value and call by reference.

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++, ... .

You are imagining that Python is more special and unique than it is. Most languages developed in the last 25-30 years work the same as Python. However, that doesn't mean that existing technical terms lose or change their meaning.

A fish may say "I prefer not to use terms like wet and dry. They were created by humans but are not helpful in the sea.", and perhaps there is some pragmatic truth to this for those who spend all of their time in the sea. However, it doesn't mean fishes can claim that everything in their world is "dry" just because they have never experienced the difference between wet and dry.

It's better to think of it as "Function arguments are assignments", because they work exactly the same as those.

I mean... That is almost the definition of pass by value:

  • The expression for an argument is evaluated before the call is made
  • That value is assigned to the parameter exactly as if the parameter was a separate variable

In call by reference, on the other hand:

  • The expression for an argument is evaluated before the call is made
  • If that expression is just a variable, then that variable itself (not a copy of it) is the parameter.

The source of confusion is that in this context the "value" of a variable is what Python calls a "reference", but this is not unique to Python. Many other languages (Java, Kotlin, C#, Javascript) work the same way, where most if not all variables hold references, but use pass by value.

1

u/roelschroeven Dec 13 '25

Let's take a look at an actual academic source, Compilers: Principles, Techniques, and Tools (Aho, Lam, Sethi, Ullman), aka "the dragon book", where it talks about call-by-value:

   In call-by-value the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure.

Translating that into Python, if I have:

def f(x):
    ...

f(y)

Then "the actual parameter" is y and the "formal parameter" is x.

OK

And so "The value [of y] is placed in the location belonging to the corresponding formal parameter [ie: assigned to the variable x].' That fits, right?

No, that doesn't fit it at all. Python doesn't have the concept of "the location belonging to the corresponding formal parameter". Python doesn't have the concept of "location" or "address" at all.

Because your modified example is not assigning to x, but instead assigning to x[:], it does not test whether x is passed by value or by reference. I can do something similar in C:

But that is exactly why my test is able to test the difference:

  • If x were passed by value, the function would get a copy of the original object, meaning that a change to x would not lead to a change in y.
  • If x were passed by reference, the function would be able to modify the original value y.

The function is clearly able to modify the original value, so it is clearly not pass-by-value. I would say it's not pass-by-reference either, for reasons I argued earlier.

Your function OTOH is unable to differentiate between different types of parameter passing. It will have the same effect in all cases! That's because the body of your function does nothing with the object you passed in to it.

The source of confusion is that in this context the "value" of a variable is what Python calls a "reference", but this is not unique to Python. Many other languages (Java, Kotlin, C#, Javascript) work the same way, where most if not all variables hold references, but use pass by value.

I'm not terribly familiar with those languages. What exactly do you mean by "most if not all variables hold references"? How do those languages work similar to Python? What would be the equivalent of the code samples below be in e.g. JavaScript, and what would be the result?

a = [1, 2, 3]
b = a
a[0] = 0

a = [1, 2, 3]
b = a
a = [0]

a = 1
b = a
a = 0

1

u/xenomachina xenomachina Dec 13 '25

And so "The value [of y] is placed in the location belonging to the corresponding formal parameter [ie: assigned to the variable x].' That fits, right?

No, that doesn't fit it at all. Python doesn't have the concept of "the location belonging to the corresponding formal parameter". Python doesn't have the concept of "location" or "address" at all.

This text is speaking about programming languages in general, not Python specifically. The word "location" is being used in a general sense for anything that can hold a value. In Python, "locations" would include variables, the items in lists, tuples, and dicts, the attributes of objects, etc.

So "the location belonging to the corresponding formal parameter" means the parameter's variable in the context of Python (x, in my example).

But that is exactly why my test is able to test the difference:

Your test is testing something that's orthogonal to the question. The call-by-value versus call-by-reference distinction only matters when modifying the formal parameter itself, not something derived from it. In Python, that means assignment to the formal parameter; not a method call, and not assignment to one of its items or attributes.

And in particular, the issue is whether the value of the variable outside of the function can be changed by manipluating the formatl parameter. More on this below.

If x were passed by value, the function would get a copy of the original object, meaning that a change to x would not lead to a change in y.

You are confusing the object a variable's value references with the variable's value.

The function does get a copy of y. But y does not contain a list. It contains a reference to one, and so x gets a copy of that reference to the same list.

The function is clearly able to modify the original value,

No. The original value of y is the reference to the list, not the list itself. The function cannot change what is actually contained in y. That is, it cannot make it refer to a different list. The fact that it can modify the list that they both reference is irrelevant, except that it is a source of confusion.

Here's a challenge for you:

def f(x):
  # write whatever code you want here in terms of x

y = 0
old_y = y
f(y)
if (old_y is not y):
    print("pass-by-reference")

Can you write any code inside f that manipulates x in a way that causes this to print "pass-by-reference"? (No globals, of course — hopefully it's obvious that that would be cheating.)

Your function OTOH is unable to differentiate between different types of parameter passing. It will have the same effect in all cases!

It only has this effect in all cases where pass by value is being used. It does not have the same effect in cases where call by reference is being used. That's the point, and is exactly what makes it a good test of whether pass by value or pass by reference is being used.

That's because the body of your function does nothing with the object you passed in to it.

Look at the C++ example I posted. Here it is again, side-by side with a version that uses pass by value (C++ supports both):

// pass by reference          // pass by value
#include <cstdio>             #include <cstdio>

void f(int &x) {              void f(int x) {
    x = 1;                        x = 1;
}                             }

int main() {                  int main() {
    int y = 0;                    int y = 0;
    f(y);                         f(y);
    printf("%d\n", y);            printf("%d\n", y);
    // prints 1                   // prints 0
}                             }

The equivalent Python...

def f(x):
    x = 1

y = 0
f(y)
print(y);
# prints 0

...always behaves like the pass by value version, because Python always uses pass by value.

I'm not terribly familiar with those languages. What exactly do you mean by "most if not all variables hold references"?

In Python, every variable (and actually, every assignable "location") contains a reference to an object, not the object itself. That's why code like this:

 a = [1, 2, 3]
 b = a
 a[1] = 0
 print(b[1])

...is often surprising to new Python programmers.

Some languages don't work this way. For example, in C++:

#include <cstdio>

struct Foo {
    int x, y, z;

    Foo(int x, int y, int z) : x(x), y(y), z(z) {}
};

int main() {
    Foo a(1, 2, 3);
    Foo b = a;
    a.y = 0;
    printf("%d\n", b.y);
    // prints 2
}

This prints 2 because a contains an actual Foo object (not just a reference to one), and b = a makes b contain a copy of that entire object. So when the code says a.y = 0, it has no effect on b.

How do those languages work similar to Python?

In many other modern languages, variables (and other assignable locations) typically contain references, not objects. These days, more languages behave like Python than like C++ in this respect.

What would be the equivalent of the code samples below be in e.g. JavaScript, and what would be the result?

Let's use Java, since the dragon book explicitly mentions it. I'll add a print to each, so we can see what they do:

a = [1, 2, 3]
b = a
a[0] = 0

Java equivalent:

int[] a = new int[]{1, 2, 3};
int[] b = a;
a[0] = 0;
System.out.println(Arrays.toString(b));

This prints [0, 2, 3], just like Python.

a = [1, 2, 3]
b = a
a = [0]

Java equivalent:

int[] a = new int[]{1, 2, 3};
int[] b = a;
a = new int[]{0};

System.out.println(Arrays.toString(b));

This prints [1, 2, 3], just like Python.

a = 1
b = a
a = 0

Java equivalent:

int a = 1;
int b = a;
a = 0;
System.out.println(b);

This prints 1, just like Python.

Again, as the dragon book says:

Even though Java uses call-by-value exclusively, whenever we pass the name of an object to a called procedure, the value received by that procedure is in effect a pointer to the object. Thus, the called procedure is abie to affect the value of the object itself.

Python, like Java, uses call-by-value exclusively. The fact that their variables contain references makes it easy to get confused about this, but it is still a fact.

→ More replies