Namespace issues...
Peter Otten
__peter__ at web.de
Sat Feb 14 07:23:54 EST 2004
cghost wrote:
> i am very confused...why does the following script modify the global list
> "l":
>
> l=[]
>
> def x():
> l.append("xyz")
>
> x()
> print l
>
> but the same script applied to a single variable doesnt..:
>
> l="moe"
>
> def x():
> l+="howdy"
>
> x()
> print l
It's even worse:
>>> def add(a, b):
... a += b
...
Now consider
>>> lst = []
>>> add(lst, ["alpha"])
>>> lst
['alpha']
>>> add(lst, ["beta", "gamma"])
>>> lst
['alpha', 'beta', 'gamma']
where add(a, b) appends b to a versus
>>> tpl = ()
>>> add( tpl, ("alpha",))
>>> tpl
()
where no apparent change takes place. The difference is that list is a
mutable type i. e. its instances can be changed anytime, whereas tuples are
immutable, i. e. they cannot be changed once they are created. For lists a
+= b is implemented to append the items in b to a. The binding of a is not
changed in the process. For immutable types this is not an option - they
cannot be altered. Therefore, for tuples a += b is implemented as a = a +
b, i. e. a new tuple containing the elements of both a and b is created and
the variable a is bound to the new tuple. In the example the binding takes
place inside a function, so you never see the new tuple unless you return
it or declare the variable as global as Vincent already pointed out.
Strings are immutable too, so
>>> s = "abc"
>>> add(s, "def")
>>> s
'abc'
as expected (hopefully).
Peter
More information about the Python-list
mailing list