Skip to content Skip to sidebar Skip to footer

Variable A Assigned To Variable B. When A Changes, Shouldn't A Change Too?

>>> a = 2 >>> b = a >>> b 2 >>> a = 20 >>> b 2 Shoudn't the last instance of b also return 20, since b is assigned to a, which changed

Solution 1:

In Python, everything is an object and when you assign something, you actually just assign a reference to the object.

So think about a variable being just a label for some object that exists somewhere—Python actually calls variables “names” for that reason.

When you do a = 2, you give the int object holding the value 2 a name a. When you now do b = a, you give the object that a references another name b. So both variables will refer to the same object. So far so good.

When you now do a = 20, you change what the name a is referring to. You are using the name to refer to a different int object which holds the value 20. This does not affect the other object that is holding the value 2; that still has the name b. So assigning something will just relabel the objects. You are never actually modifying any object that way.

This is different to when you mutate an object though. The most common example is a list:

a = ['hello']
b = a

Just like before, a and b are names for the samelist object. If you now mutate b by calling b.append('world'), you are mutating the object that b references. But a still refers to the samelist object, so when looking at a, you will see those changes too:

>>>a = ['hello']>>>b = a>>>b.append('world')>>>a
['hello', 'world']

Solution 2:

In the example, b is initialized as the quantity that is stored in a, which is 2. Then, a is reassigned the value of 20. However, that does not change b as int objects are immutable. In other words, b has the value that a was, but once a is changed, it does not effect is stored in b

a = 2b = a #here, storing the contents of a in b#b now stores 2a = 20#here, only changes the value that is stored in a.#b is still 2

Edit:

Here is an example where b is assigned to a:

a = 2b = 3a = b #now, a stores the value that b contains#a is now 3#b is still 3

Post a Comment for "Variable A Assigned To Variable B. When A Changes, Shouldn't A Change Too?"