Default arguments, object sharing, name lookup and others

Maciej Sobczak no.spam at no.smap.com
Mon Dec 22 11:20:09 EST 2003


Hi,

Playing around with the Python Tutorial I found the following definition:

def f(a,L=[]):
	L.append(a)
	return L

then:

f(1)
f(2)
f(3)

will accumulate the values appending them to the *same* list.

Now:

def f(a,s=''):
	s = s + a
	return s

f('hello')
f('world')

This will not cause value accumulation.
Interestingly, this will neither:

def f(a,L=[]):
	L = L + [a]
	return L

which is most confusing for me.

I do not understand how this works (the first one).
I would like to ask you for some explanation, especially:
- where is the object stored if it is shared between subsequent calls? 
how it is found?
- why does it work for lists and not for strings?
- why does it work for lists only when the append method is used?

My "native" language is C++. Feel free to use analogies, where appropriate.

Thank you very much for any light,

-- 
Maciej Sobczak : http://www.msobczak.com/
Programming    : http://www.msobczak.com/prog/





More information about the Python-list mailing list