Created on 01-09-2019 12:37 PM - edited 09-16-2022 07:03 AM
Can anyone explain me the problem with the following piece of code-
>>> def func(n=[]):
#playing around
pass
>>> func([1,2,3])
>>> func()
>>> n
Created 01-09-2019 07:16 PM
Do I read that right?
Does a call to
func()
return "n" in your case??
And is that your problem/question??
Created 01-11-2019 12:07 PM
The request for n raises a NameError. This is since n is a variable local to func and we cannot access it elsewhere. It is also true that Python only evaluates default parameter values once; every invocation shares the default value. If one invocation modifies it, that is what another gets. This means you should only ever use primitives, strings, and tuples as default parameters, not mutable objects.
Created 05-26-2019 02:42 AM
By mentioning "n=[]" as an argument to your func() definition, you mean to provide an empty Python list as the default parameter.
The problem is with your code that neither you are printing "n" nor it is being returned by the func(). You can try and use the below-updated code:
>>> def func(n=[]): ... print(n) ... >>> func([1,2,3]) [1, 2, 3] >>> func() []