Support Questions

Find answers, ask questions, and share your expertise

Problem with the following piece of code?

Can anyone explain me the problem with the following piece of code-

>>> def func(n=[]):
#playing around
pass
>>> func([1,2,3])
>>> func()
>>> n

3 REPLIES 3

Explorer

Do I read that right?

Does a call to

func()

return "n" in your case??

And is that your problem/question??

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.

New Contributor

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()
[]
Take a Tour of the Community
Don't have an account?
Your experience may be limited. Sign in to explore more.