Namespace issues...

C

cghost

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
 
V

vincent wehren

| 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"

Python decides that a variable is local if it's ever *assigned a value in a
function*.
In this example you assign a value to l. In the first example, you do not
(you change list l
"in place"), so here this optimization does not take place.

You have to be explicit about l being a global if you assign a value to it
using the "global" statement as in:
def x():
global l
l+="howdy"

HTH,

Vincent Wehren



|
| x()
| print l
 
P

Peter Otten

cghost said:
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:
.... 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
()

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
'abc'

as expected (hopefully).

Peter
 

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

Forum statistics

Threads
474,183
Messages
2,570,965
Members
47,513
Latest member
JeremyLabo

Latest Threads

Top