Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking more than one list as argument for a function

Tags:

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.

like image 258
Antoine Gallix Avatar asked Feb 28 '14 14:02

Antoine Gallix


People also ask

Can a list be passed as an argument to a function?

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.

How can you accept multiple arguments into a 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.

Can a function have multiple arguments?

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.

What is unpacking arguments in Python?

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.


1 Answers

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.

like image 168
thefourtheye Avatar answered Oct 02 '22 09:10

thefourtheye