Search code examples
pythonmutable

testing mutability in python


I am doing a simple test to verify mutability I have a variable var

I want to verify that = assignment operator changes the value at same memory location for it I a doing

var = 1

To print address of var I do

hex(id(var)) it gives me '0x1b65158' then I assign new value var = 2 but now hex(id(var)) is changed to '0x1b65140' if it is changing the same location it should be return same isnt it? please explain

Note : I dont want to do same assignment mentioned here. I am trying to understand how it is assigning mutably. And I am not trying to create constant here.


Solution

  • Some implementations of Python keep an array of integer objects for all integers between -5 and 256. Meaning that when you create an int in that range you actually just get back a reference to the existing object.

    For example:

    id(1)
    --> 8790876942080
    x = 1
    id(x)
    --> 8790876942080
    

    So, when you assign a new values 1 or 2 to your variable, you actually assign the reference to these exisiting objects.

    This behaviour, as I mentioned above, is not consistent for all integers, for example:

    id(5555555555)
    --> 89108592
    x = 5555555555
    id(x)
    --> 89109104
    

    You can read more here:

    1. ID Function

    2. is Operator