In Python, immutable objects include numbers, strings, and tuples. With the last two everything is clear, but regarding the numbers there. Let's write this code:

a = 7 a = 5 

As a result, the number 5 will be stored inside the variable a , but the numbers are immutable, how does it come out?

  • 6
    Variables are changeable, numbers are unchangeable, do not confuse - andreymal

2 answers 2

Numbers are immutable, but in your example you changed not a number, but a variable.

And in python, variables are not objects, keepers of references to objects. Those. when a = 7 variable stores the reference to the object 7 , and after a = 5 variable now stores the reference to another object - 5 .

If you run and check, you will see the current links to the objects:

 a = 7 print(hex(id(a)), hex(id(7))) # 0x71106160 0x71106160 a = 5 print(hex(id(a)), hex(id(5))) # 0x71106120 0x71106120 

    Instead of conducting thought experiments, check in practice:

     a = 7 b = a # Сохраним то, что в `a` прямо сейчас a = 5 # "Изменим" (?) число в `a` a is b # Верно ли, что `a` и `b` содержат одно и то же значение? # => False 

    And if you look at the value in b (it’s also the past value a , 7 ), then you can see that it remains the same.