[Tutor] How default arg of function works

Alan Gauld alan.gauld at yahoo.co.uk
Thu Jun 14 03:28:37 EDT 2018


On 14/06/18 08:04, Deepak Dixit wrote:

> def test2(nums=[]):
>         nums.append(len(nums));
>         return nums
> 
> print 'test2()', test2()
> print 'test2([1,2,3])', test2([1,2,3])
> print 'test2([1,2])', test2([1,2])
> print 'test2()', test2()
> print 'test2()', test2()
> 
> Calling test2
> ========================================
> test2() [0]
> test2([1,2,3]) [1, 2, 3, 3]
> test2([1,2]) [1, 2, 2]
> test2() [0, 1]
> test2() [0, 1, 2]
> 
> I am assuming that in test1() we are not doing any modification in the
> passed list and because of that its working as per my expectation.

Correct. You are still dealing with 2 separate objects(see below)
but you don't modify anything so it looks like it works as you
expected.

> But when I am calling test2() with params and without params then both are
> using different references.  Why ? Can you please help me to understand
> this.

When you create a default value for a function parameter Python
creates an actual object and uses that object for every invocation
of the function that uses the default. If the object is mutable
(a list or class instance, say) then any modifications to that
object will stick and be present on subsequent calls.

Thus in your case the first call of the function the list is
empty and has len() 0, the second call it still has the zero
stored so len() is now 1, and so on.

But when you call the function without using the default
Python does not involve the default object at all, it uses
whichever object you provide.

The same applies to your tst1 function. Each time you use
the default call the same empty list object is being printed.
But because you don't modify it it always appears as
an empty list.

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