confusion about variable scope in a class

andrew cooke andrew at acooke.org
Sat Feb 14 11:22:19 EST 2009


it's not a scope issue.  you are confusing variables and objects.

a variable is a box that can hold an object

so x = 2 puts the object '2' in the box 'x'.

following that with x = '3' changes the box 'x' to hold the object '3'.

but lists are also boxes, different from variables.

so x = [1,2,3]

puts the a list object, that is a box that contains 1, 2 and 3, in 'x'

then y = x

puts THE SAME list object in box 'y'.

then y[1] = 4 changes the second item in the list's box to 4

the print x gives "[1,4,3]" because you have changed contents of the list.

in contrast x = 3 then y = x then y = 4 does not change x because you care
changing variables, not list contents.

to fix your code, you need to copy the list

x = [1,2,3]
y = list(x) # copy
y[1] = 4
print x
[1,2,3]

surely this is ina faq?  it comes up once a day...

andrew



gyro wrote:
> Hi,
> I was writing a Python script to perform some data analyses and was
> surprised by some behavior I noted. A simple test program illustrating
> the behavior is below.
> I do not understand why the value of 'data' is being modified. I am
> obviously missing something obvious, and would certainly appreciate an
> explanation of why this is happening.
>
> Thank you.
>
> -gf
>
> ----------
>
> #!/bin/env python
>
> class TestPop(object):
>     def round1(self,data1):
>         t = data1.pop(-1)
>
>     def round2(self,data2):
>         t = data2.pop(-1)
>
>     def tester(self):
>         data = range(10)
>         self.round1(data)
>         print data
>         self.round2(data)
>         print data
>
> if __name__ == '__main__':
>     tp = TestPop()
>     tp.tester()
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>





More information about the Python-list mailing list