confusion about variable scope in a class

G

gyro

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()
 
D

Diez B. Roggisch

gyro said:
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.


Lists are mutables, and python passes around references to objects, not
copies.

So if you want a copy, you need to create one explicit, either by using e.g.


new_list = list(old_list)

which will create a shollow copy of the list, or by using the
library-module "copy" that also offers a "deepcopy" function.


Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top