[Tutor] scoping issues

Alan Gauld alan.gauld@blueyonder.co.uk
Tue May 6 17:50:02 2003


> This is easy:
>
> mylist = []
> def meth():
>     mylist.append('a')
>     mylist.append('b')
>     mylist.append('c')
>
>
> The problem is, I want to re-set mylist on each call to meth() so
that it
> only has the things from the last call.  If I call this twice, I
get:

So move the mylist declaration into the method and then return
the result. This is generally a better way to do things anyway:

def meth():
     mylist = []
     mylist.append('a')
     mylist.append('b')
     mylist.append('c')
     return mylist

Now you can assign the value anyplace you like:

l1 = meth()  #->['a','b','c']
l2 = meth()  #->['a','b','c']
l1 = meth()  #->['a','b','c'] ie not two sets

> I tried resetting mylist back to [] in meth():

You needed to declare mylist as global, otrherwise you just
created a local variable inside the method and never changed
the external one. But using a lobal variable is not good
practice, better to do as I did above...

> (and I'm not sure I fully understand this)  there seem to be two
"mylist"
> variables, modulename.mylist and another that I'm not sure how to
even
> access.

The other one only existed inside meth(), as soon as you exited
meth() it was garbage collected.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld