[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: is != == (Re: [pygame] Sticky Variables: Terrain Loading)




On Mar 12, 2008, at 1:06 PM, Ian Mallett wrote:

Hmm.
This might be associated with another problem I've been having.
NOT really tried--not near a python interpreter...
If I have something like:
x = [1,2,3,4,5,6]
y = x
then changes to y change x.

That statement is a big misleading, it implies that the changes happen in two places, but both y and x point to the same object, they are in fact the same thing with two different names. You can think of y as an alias for x.


 So I've had to:
y = [x[0],x[1],x[2],x[3],x[4],x[5]]
...which doesn't change x when y is changed.

Yipes!

You might have an easier time with:

y = list(x)

which makes a new list object with the same elements as x. Note this is a "shallow" copy though and although x and y are separate list objects, they have the same objects as elements. This is not important if the elements are immutable (such as strings, ints, etc). But if they are mutable objects like lists or dicts then things might not behave as you expect. Consider this:

>>> x = [[1,2], [3,4]]
>>> y = list(x)
>>> x is y
False
>>> x == y
True
>>> x[0].append(3)
>>> y
[[1, 2, 3], [3, 4]]
>>> x == y
True

Note the same thing would happen copying your way (y = [x[0], x[1]]). Luckily this is not a very common problem, the solution is to only use immutable elements (e.g., tuples) or use deepcopy:

http://docs.python.org/lib/module-copy.html

-Casey