Understanding python's memory model

memory, python

Solution

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

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

`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:

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

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

When you execute this one:

y = 1000000

two more things happen:

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

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

Problem

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!

Original source

Related problems