Nant
Nant

Reputation: 569

Memory allocation of python object

I have the following code:

a = 2
b = a

a = a + 2
print (a)
print (b)

My question is why does b print out as 2 and not 4? If you assign a to b, doesn't b always reference to the memory of a?

Thanks

Upvotes: 3

Views: 680

Answers (3)

Rocky Li
Rocky Li

Reputation: 5958

Because you have reassigned x to a new location by x = x + 1, and it's not about immutability.

For checking:

x = 2
y = x

>>> id(x), id(y)
(26726784, 26726784) # same

Then, change this:

x = x+1

>>> id(x), id(y)
(26726760, 26726784) # not same, because x reassigned to a new reference location.

If you do the same for list, which are mutable, you'll have the same result:

x=[5]
y=x

>>> id(x), id(y)
(139890260976056, 139890260976056)

on assignment:

x = x + [5]

>>> id(x), id(y)
(139890260094344, 139890260976056) # not same, id reallocated on assignment
>>> x, y
([5, 5], [5])

You'll see mutable behavior on list by using x.append(5), where both x and y change as you're modifying the object itself. But in this case, it's not the mutability of the object that are causing the difference. It's the assignment x=something else that changed the reference.

An interesting property about int in python is that smaller ones are pre-allocated. For instance, if you do:

x = 5
y = x
x = 5
id(x) == id(y) # True

The id will be the same, however, if you do:

x = 5000000000000
y = x
x = 5000000000000 # same as previous.
id(x) == id(y) # False

This is due to small integers having pre-allocated location while large ones don't. As such reassignment for large integer will find a different location instead.

This validates @juanpa.arrivillaga's point that this is due to assignment, not immutability.

Upvotes: 3

sacuL
sacuL

Reputation: 51335

The variable gets re-allocated to a new address when you re-assign a:

>>> a = 2
>>> b = a
# get memory address for a and b
>>> id(a)
4357961072
>>> id(b)
4357961072
# they are the same

# now reassign
>>> a = a + 2
# id of a has changed
>>> id(a)
4357961136
# id of b has not
>>> id(b)
4357961072

Upvotes: 2

Filip Młynarski
Filip Młynarski

Reputation: 3612

Not all python objects are mutable, here's list of which are.

Upvotes: 0

Related Questions