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!
>Solution :
The key difference is that input.append(value) is an expression and input[value] = value is not (it is just a statement). The return statement can only take an expression as a parameter (or no parameters to return None).
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.