Search code examples
pythonpython-2.7iterable-unpacking

How can I unpack tuple when other variables are needed?


According to this, I can call a function that takes N arguments with a tuple containing those arguments, with f(*my_tuple).

Is there a way to combine unpacking and unpacked variables?

Something like:

def f(x,y,z):...
a = (1,2)
f(*a, 3)

Solution

  • The code you supplied (f(*a, 3)) is valid for python 3. For python 2, you can create a new tuple by adding in the extra values. Then unpack the new tuple.

    For example if you had the following function f:

    def f(x, y, z):
        return x*y - y*z
    
    print(f(1,2,3))
    #-4
    

    Attempting your code results in an error in python 2:

    a = (1,2)
    print(f(*a,3))
    #SyntaxError: only named arguments may follow *expression
    

    So just make a new tuple:

    new_a = a + (3,)
    print(f(*new_a))
    #-4
    

    Update

    I should also add another option is to pass in a named argument after the * expression (as stated in the SyntaxError):

    print(f(*a, z=3))
    #-4