If I have a function like:
def f(a,b,c,d):
print a,b,c,d
Then why does this works:
f(1,2,3,4)
f(*[1,2,3,4])
But not this:
f(*[1,2] , *[3,4])
f(*[1,2] , *[3,4])
^
SyntaxError: invalid syntax
?
EDIT : For information, the original problem was to replace one of the argument in a function wrapper. I wanted to replace a given member of the inputted *args and tried something like:
def vectorize_pos(f,n=0):
'''
Decorator, vectorize the processing of the nth argument
:param f: function that dont accept a list as nth argument
'''
def vectorizedFunction(*args,**kwargs):
if isinstance(args[n],list):
return map(lambda x : f( *(args[:n]) , x , *(args[n+1,:]), **kwargs),args[n])
else:
return f(*args,**kwargs)
return vectorizedFunction
That's where the question arose from. And I know there is other way do do the same thing but only wanted to understand why unpacking one sequence worked but not for more.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function. This video doesn't have any notes.
Unpacking function arguments are used when we want to unpack list/tuple/dict during the function call. Packing function arguments are used when we don't the number of parameters passed during the function call. The same function can be used for the different number of parameters.
Because, as per the Function call syntax, this is how the argument list is defined
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression]
| keyword_arguments ["," "*" expression]
["," keyword_arguments] ["," "**" expression]
| "*" expression ["," keyword_arguments] ["," "**" expression]
| "**" expression
So, you can pass only one * expression
per function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With