Writing an immutable object in python

Magnus Lycka lycka at carmen.se
Mon Oct 17 12:09:31 EDT 2005


Mapisto wrote:
> Hi,
> 
> I've noticed that if I initialize list of integers in the next manner:
> 
> 
>>>>my_list = [0] * 30
> 
> 
> It works just fine, even if I'll try to assign one element:
> 
> 
>>>>id( my_list[4] )
> 
> 10900116
> 
>>>>id( my_list[6] )
> 
> 10900116
> 
>>>>my_list[4] = 6
>>>>id( my_list[4] )
> 
> 10900044
> 
>>>>id( my_list[6] )
> 
> 10900116
> 
> The change in the poision occurs becouse int() is an immutable object.

No, it happens because you assign my_list[4] to a different object.
Obviously, 0 and 6 can't be located in the same place in RAM.

The difference lies in doing something like "my_list[n] = X" rather
than changing the state of a shared existing object as in something
like "my_list[n].f(X)".

> if I will do the same with a user-defined object, This reference
> manipulating will not happen. 

Really?
 >>> class C:
...    pass
...
 >>> my_list = [C()]*30
 >>> id(my_list[4])
1003056
 >>> id(my_list[6])
1003056
 >>> my_list[4] = C() # Another instance
 >>> id(my_list[4])
986048
 >>> id(my_list[6])
1003056



More information about the Python-list mailing list