On 12/07/2019 15:24, Gursimran Maken wrote:

> Can someone please explain me the reason for below output.

You've been bitten by one of the most common gotchas in Python :-)

> def fun(n,li = []):
>     a = list(range(5))
>     li.append(a)
>     print(li)
> 
> fun(4)
> fun(5,[7,8,9])
> fun(4,[7,8,9])
> fun(5) # reason for output (why am I getting to values in this output.)

When you define a default value in Python it creates the default value
at the time you define the function. It then uses that value each time a
default is needed. in the case of a list that means Python creates an
empty list and stores it for use as the default.

When you first call the function with the default Python adds values to
the defaiult list.

Second time you call the function using the default Python adds (more)
values to (the same) default list.

Sometimes that is useful, usually it's not. The normal pattern to get
round this is to use a None default and modify the function like so

def fun(n,li = None):
    if not ni: ni = []   # create new list
    a = list(range(5))
    li.append(a)
    return li  # bad practice to mix logic and display...

HTH

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

Reply via email to