[Tutor] mutable types

Knacktus knacktus at googlemail.com
Tue Nov 2 14:31:01 CET 2010


Am 02.11.2010 13:51, schrieb John:
> Hello, I thought the following should end with G[1] and G[0] returning
> 20. Why doesn't it?
>
> In [69]: a = 10
"a" is a reference to an immutable object of type int with value 10. 
Somewhere in memory is an object of type int with value 10 stored. This 
object cannot be changed. "a" is just a name that references to the 
memory adress.
> In [70]: G = {}
> In [71]: G[0] = [a]
now, G[0] holds a reference to a mutable object of type list with an 
immutable object of type int with value 10 as its content. So, your list 
holds as item the memory adress of an object int with value 10. Your 
list knows nothing about other names (like "a"), that refer to the same 
adress in memory. You have handed over the object to the list (or memory 
adress of the object), not the name "a".
> In [72]: G[1] = G[0]
> In [73]: a = 20
Now, you've created a *new* immutable object of type int with value 20.
"a" now refers to the adress of the new integer object. "a" has 
forgotten everything about its former reference to the object of type 
int with value 10.
You have *not* changed the "old" object of type int with value 10. Your 
list in G[0] still holds the memory adress of the first int with value 10.
> In [74]: G[1]
> Out[74]: [10]
> In [75]: G[0]
> Out[75]: [10]
>
> ??
Now, if you would keep a reference to the list you've handed over to the 
dict, you could change the content of the list, as the list is mutable.

 >>> a = [10]
 >>> G = {}
 >>> G[0] = a
 >>> G[0]
[10]
 >>> a[0] = 20
 >>> G[0]
[20]

Take care of some operations that return a copy of the list:

 >>> a = a[:]
Now, "a" refernces to a new list, which has also one item of type in 
with value 20. But it's not the same list as originally!
 >>> a[0] = 30
Changing this new list ...
 >>> G[0]
[20]
does not affect the list, we stored in the dict.

HTH,

Jan
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list