Doubt about 'default argument values'

8 views
Skip to first unread message

Flávio Santos

unread,
Feb 3, 2006, 3:14:22 PM2/3/06
to pyt...@googlegroups.com
Hi community!

I'm a beginner on Python.
I was reading the Python Tutorial (http://docs.python.org/tut/node6.html#SECTION006700000000000000000) and I got confused with the following code:

def f(a, L=None):
1. if L is None:
2. L = []
3. L.append(a)
4. return L
Why the output for the code:
f(1)
f(2)
f(3)
is:
[1]
[2]
[3]
?????????

If the code
L=None
is executed only once, I thought that the line 1 was also executed once, since the line 2 makes the L value to be different of None.

Thanks in advance,
Flávio Barata

zavandi

unread,
Feb 3, 2006, 4:00:40 PM2/3/06
to pyt...@googlegroups.com
On 2/3/06, Flávio Santos <flavio...@gmail.com> wrote:
> [...]

> If the code
> L=None
> is executed only once, I thought that the line 1 was also executed once,
> since the line 2 makes the L value to be different of None.

It's not executed only once. The default value is evaluated once, but
the L is assigned every time. The same in the example above with 'def
f(a, L=[])' -- the value is assigned to L every time, but it's the
same object. Try modifying it like this to convince yourself it's the
same object:

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

WhoAndWho

unread,
Feb 14, 2006, 2:39:04 AM2/14/06
to python
Please note:in python, default arguments will be only evaluated once.
So in the code below:

def f(a, L=None):
1. if L is None:
2. L = []
3. L.append(a)
4. return L

when the function f is executed, the default argument None is evaluated
once,and assigned to
the local variable L. But the if conditional statement makes L lose the
reference to the object None.By contrast, in the code presented by
zavandi, L will always reference the object occuping the memory slot
which was occupied by the object [].So,if you run the function call
f(1),f(2),f(3),the result will be:
[1],[1,2],[1,2,3]
Here, when the f(1) is executed, L references the memory slot occupied
by the object [], and later in-place change still makes L reference the
that same memory slot,however the contents change to [1].when the f(2)
is executed, L still references the object occuping the memory slot
which was occupied by the object [1],so the result difference takes
place.

Reply all
Reply to author
Forward
0 new messages