If I remember how that works right, there is a single empty list that is 
created and used for all the calls that use the default argument, and then your 
function modifies that empty list so it is no longer empty, and that modified 
list is used on future calls. (Not good to use a mutable as a default 
parameter).

A better solution would be to make the default something like None, and test if 
at the beginning of the function li is None, and if so set it to an empty list, 
and that empty list will be in function scope so it goes away and a new one is 
created on a new call.

> On Jul 12, 2019, at 10:24 AM, Gursimran Maken <gursimran.ma...@gmail.com> 
> wrote:
> 
> Hi,
> 
> Can someone please explain me the reason for below output.
> 
> Program:
> 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.)
> 
> Output:
> [[0, 1, 2, 3, 4]]
> [7, 8, 9, [0, 1, 2, 3, 4]]
> [7, 8, 9, [0, 1, 2, 3, 4]]
> [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
> 
> Thank you,
> Gursimran
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to