[Tutor] How to use function with default values ?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Aug 7 04:19:11 EDT 2016


On 07/08/16 04:22, rishabh mittal wrote:

> I am new to python and come from C language background. I couldn't able to
> understand this
> 
>  >>> def f(a, L=[]):
> ...     L.append(a)
> ...     return L
> ...
> 
>>>> print(f(1))
> [1]
> 
>>>> print(f(2))
> [1, 2]

>>>> def f(a, L=10):
> ...     L=10+a
> ...     return L
> 
>>>> print(f(1))
> 11
> 
>>>> print(f(1))
> 11

> In the first example if i call function f then it looks like L is treated
> as a static object which is not reinitialized in the subsequent function
> calls.

That's more or less correct. The default object is created at definition
time and that same object is used for any invocation of the function
that does not provide an explicit value.

> 
> But in the second example, it seems to be reinitialized in the subsequent
>  calls. Can anyone explain this or point me to the discussion if it is
> asked before.

The issue is immutability. In the first
case you create a default object which is a list.
Lists are mutable so you can add items to it.
In the second case you create a default integer
object which is immutable. (And it's important to
remember that it is an integer object not an
integer placeholder or reference.)

So in the first case when you do

L.append(a)

you add an item to the list


But in the second case when you do

L = 10+a

You create a new integer object that *replaces*
the default. The default object is still there
ready to be used next time you call the function.
It's just the local variable L that has its
value changed.

And in case you are wondering, it would not have
made any difference if you had done

L = L+a  # or L += a

The effect would be the same. The immutable
initial value would be replaced by a new integer
object.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list