Python: Object Has A List As Attribute But Stores Only A Reference And Not The List
I work in Python 2.4 (comes with the system). I try to compile a list of objects. Each Object has an attribute that is a list of other objects. Whatever I do it seems to me that
Solution 1:
Ok thats because in Python all are references. I'll explain with a simple example:
>>>l = [0, 0, 0]>>>a = l>>>a[0] = "Changed">>>print (l)
["Changed", 0, 0]
>>>print (a)
["Changed", 0, 0]
This happend because with the statement a=l
we have just put another name to the object [0, 0, 0]
To achive what you want you can use copy
module
>>>import copy>>>l = [0, 0, 0]>>>a = copy.copy(l) # This is the only change.>>>a[0] = "Changed">>>print (l)
[0, 0, 0]
>>>print (a)
["Changed", 0, 0]
Post a Comment for "Python: Object Has A List As Attribute But Stores Only A Reference And Not The List"