Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding python's memory model [duplicate]

Tags:

python

memory

Consider the following log:

>>> y = 20000
>>> id(y)
36638928
>>> y = 1000000
>>> id(y)
36639264

As you can see, after changing the value of y, it's id changed as well.
Does it mean that int is immutable? what is happening behind the scenes?

Thanks!

like image 639
SuperStamp Avatar asked Jun 05 '26 17:06

SuperStamp


1 Answers

Yes, integers are immutable. What you need to realize is that:

  1. A variable is simply a name which you use to reference an object.

  2. 20000 and 1000000 are two unique integer objects. This means that they will never share the same memory address simultaneously.

In simple terms, when you execute this line:

y = 20000

two things happen:

  1. An integer object 20000 is created in the object space.

  2. A name y is created in the namespace and pointed to that object.

When you execute this one:

y = 1000000

two more things happen:

  1. A new integer object 1000000 is created in the object space.

  2. The name y is changed to point to that object instead of 20000.