[Tutor] How default arg of function works

Deepak Dixit deepakdixit0001 at gmail.com
Thu Jun 14 03:40:29 EDT 2018


You mean that for default args and passed args of mutable type, python uses
different object and same reference will be used for further calling of the
function.
Now one more thing I want to ask you that how can I get deep understanding
of python like how list, dictionary works internally and other topics , is
it only possible after more and more practice. Any suggestions from your
side will be really helpful for me.

On Thu, Jun 14, 2018, 1:00 PM Alan Gauld via Tutor <tutor at python.org> wrote:

> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list