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

Re: [pygame] Variables linking to eachother



On Sun, 23 Mar 2003, campbell barton wrote:
> 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 Python, everything is an object. When you assign a variable, you bind a 
local name into an object. Also, several variables can be bound to the 
same object.

The above example prints 1 by the way. This is because x = 2 binds the 
name 'x' into another number. This does not affect the name 'y'. The 
is-operator in Python will tell you if two variables point to the same 
object in memory. Eg.

y = 1
x = y
print x is y
1
x = 2
print x is y
0

Two variables pointing to the same object doesn't usually cause any 
surprising side effects when dealing with immutable objects such as 
numbers. With lists, however, you have to think more careafully:

a = [1,2,3]
b = a
a[0] = 10 ## assigning to an index does not rebind the name 'a'
print b
[10,2,3]

Usually what you do in this situation, if you do not wish the object to be 
shared, is to copy the list.

a = [1,2,3]
b = a[:]
a[0] = 10
print b
[1,2,3]

I hope this helps.

--
Sami Hangaslammi