[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [pygame] Variables linking to eachother



> 
> I have had this problem a few times.
> When I assign a variable, sometimes they 'link' to eachother eg
> 
> x = 1
> y = x
> x = 2
> print y
> 2
> 
> In this example of what is the problem is, however this example works.
> 
> I had the problem when duplicating an item in a list.
> platformList.insert(1, platformList[selectedPlatform]) # This 
> had problems, both items linked togather and I could not 
> change one part of the list item without the other changing too.
> 
> However turning the list item into a string and eval()'ing it 
> worked without the linking problem.
> platformList.insert(1, eval( str(platformList[selectedPlatform])))
> 
> Does anyone know what is going on, how to get around this 
> problem a better way?

Presumably the elements of platformList are objects as opposed to simple
types like integer.

In Python, all objects are actually references to that object. If you assign
an object to another object, then the two objects refer to the same thing. 

If you want to assign a copy of an object to an other object and have the
two refer to different copies of that original object, use the
copy.deepcopy() function to generate a copy, i.e

import copy
platformList.insert(1, copy.deepcopy(platformList[selectedPlatform]))

Alain Désilets