Home > Net >  Putting asterisk before function call in python
Putting asterisk before function call in python

Time:08-13

I am stuck with python syntax. I have seen people using a * before a function call in python. Tried writing a sample code, but not sure how this syntax works. The code below is not compiling. It would be really great if someone can explain this syntax.

    def data(value):
        return get_value(*get_ab(value))
        
    
    def get_value(value):
        x= value;  
        return x
    
    def get_ab(value):
        return value
    
    final_value= data("manu")
    
    print(final_value)

CodePudding user response:

Consider this completely contrived example.

def list_to_tuple(l):
    return l[0], l[1]


def output(x, y):
    print(x, y)


l = [1, 2]
output(*list_to_tuple(l))

Here, it looks like the * is "before the function call", but really it is before the value returned by the function call. In this case, a tuple. So the asterisk, unpacks that tuple's values into the parameters for output.

  • Related