Good day, brilliant Stack Overflow Community. I noticed an interesting behavior regarding Python function when input as a dictionary.
When we use the empty list as a default argument, we can return that list while appending some value.
def func_list(value,input=[]):
return input.append(value)
I would expect the same thing to apply when empty dictionary as an argument. such as:
def func_dict(value,input={}):
return input[value] = value
However, Python will raise a Syntax Error, and I can only do something like:
def func_dict(value,input={}):
input[value] = value
return input
I am wondering why? Thank you so much!
PS. Please feel free to modify the question, and apologize if my expression of the question is not clear enough!
CodePudding user response:
The key difference is that input.append(value)
is an expression and input[value] = value
is a statement. You cannot return
a statement as it has no value.
You CAN do this:
def func_dict(value,input={}):
return input.update({ value: value }) or input
How this works is that dict.update()
returns None so we return the (now updated) input
instead. I know it's ugly but can't think of a better one.
CodePudding user response:
On another note, the word input
is a protected word in python and is used for interactions with the user, you may want to use another parametername as you override the default function when using it the way you do right now.
Here's the documentation regarding input: https://docs.python.org/3/library/functions.html#input