[Tutor] re: Scoping question

Magnus Lycka magnus@thinkware.se
Sat, 14 Sep 2002 15:18:46 +0200


At 18:16 2002-09-09 +0000, Charlie Clark wrote:
>list is a key word in Python for turning other objects into lists so it's a
>good idea to use another name, although Python will let you reassign it
>without complaining.

To be picky, list() is a built-in function, not
a keyword. Using a keyword (such as "in", "for"
or "print") as a vaiable name is a syntax error.

> > And finally, why does the assignment to a list element execute
> > successfully?

If you write

l =3D 5

you let go of whatever object l might have pointed at before, and
refer to the integer object 5 instead. If you write

l[0] =3D 5

you don't. 'l' still points to the same object as it did -- a list,
and you change the content of the first item of this list. It's
not at all the same thing.

Maybe it's unfortunate that Python uses that syntax for assignment
to slices and list elements. I guess you wouldn't have asked that
question if the syntax had been:

l.updateElement(0,5)

Besides, if you think about it, you realize that it really has to
be like this.

a =3D "m"

def x():
     a =3D 5
     print a

Here, it's certainly clear to me that a in x() should be a
local variable. If we turn it around:

a =3D "m"

def x():
     print a
     a =3D 5

In this case it seems reasonable that 'a' in x() is still
local, and that the code is in error.

def x():
     a =3D a + 1

or

def x():
     a +=3D 1

are just variations of that. But with something like

a =3D []

def x():
     a[0] =3D 5

it's a completely different thing. First of all, we don't
reassign 'a' to a different object. We fill this mutable
object with data. Secondly, if we would have imagined that
'a' in x() was local here, the code above would have been
incorrect. If 'a' is local, it's so-far not defined, and
then it's not a list or anything else that you can make
an element assignment to. It would be as incorrect as writing

'a[0] =3D 5' in the global scope without assigning 'a' to a list
or other mutable sequence first.




--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se