Support Questions
Find answers, ask questions, and share your expertise
Announcements
Alert: Welcome to the Unified Cloudera Community. Former HCC members be sure to read and learn how to activate your account here.

Problem with the following piece of code?

Highlighted

Problem with the following piece of code?

New Contributor

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

Re: Problem with the following piece of code?

New Contributor

Do I read that right?

Does a call to

func()

return "n" in your case??

And is that your problem/question??

Re: Problem with the following piece of code?

New Contributor

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.

Re: Problem with the following piece of code?

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()
[]