[Tutor] strange difference between two functions

Karl Pflästerer sigurd at 12move.de
Mon Dec 15 12:04:58 EST 2003


On 15 Dec 2003, Hameed Khan <- hameedkhaan at yahoo.com wrote:

>   i was reading the tutorial comes with python
> documentation. i found 2 example functions in it. but
> i cant understand these functions because of their
> different output. so if any one of you out there can
[...]


> # function one #
>>>> # function one
> ... def f(a, L=[]):
> ...     L.append(a)
> ...     return L
> ...
[...]
> # function two #
>>>> # function two
> ... def f2(a, L=[]):
> ...     if not L:
> ...             L = []
> ...     L.append(a)
> ...     return L
> ...
[...]

The explaination is in the paragraph above these functions in the
tutorial;
I'll cite it here:
,----
| *Important warning:*  The default value is evaluated only once.  This
| makes a difference when the default is a mutable object such as a list,
| dictionary, or instances of most classes.  For example, the following
| function accumulates the arguments passed to it on subsequent calls:
`----

So what happens if you call f? 

As we can read the default value is only once evaluated; this means that
every time we call that function without explicitly giving an value for
L the default value is taken which happens to be the same object (the
identic object). We can see that if we change the definition a bit. 
Python has the function `id()' which returns a number (an adrress). if
two objects have the same id value they are the same object (also in
memory; they exist only once).

So change the above definition of to:

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

Now at the repl we see:

In [26]: f(1)
ID=  11974284
Out[26]: [1]

In [27]: f(2)
ID=  11974284
Out[27]: [1, 2]


So you see the very same list is used at every function call.


Now change f2 the same way and you get:

def f2(a, L=[]):
     print 'ID1= ', id(L)
     if not L:
             L = []
     print 'ID2= ', id(L)
     L.append(a)
     return L

In [29]: f2(1)
ID1=  11976588
ID2=  11976652
Out[29]: [1]

In [30]: f2(2)
ID1=  11976588
ID2=  12013612
Out[30]: [2]


You see the default value is also evaluated only once but that list
isn't used when the appending happens but the (every function call)
newly created list L.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list