CIsForCookies
CIsForCookies

Reputation: 12837

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)

Upvotes: 2

Views: 577

Answers (3)

pault
pault

Reputation: 43544

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

Upvotes: 5

chepner
chepner

Reputation: 532418

A little heavy, but you can use functools.partial to partially apply f to the arguments in a before calling the resulting callable on 3.

from functools import partial

partial(f, *a)(3)

This is more useful if you plan on making a lot of calls to f with the same two arguments from a, but with different 3rd arguments; for example:

a = (1,2)
g = partial(f, *a)
for k in some_list:
    g(k)  # Same as f(1,2,k)

Upvotes: 2

ddor254
ddor254

Reputation: 1628

as @pault said - you can create a new tuple , and you can do another thing which is:

pass the *a as the last variable to a function, for example :

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

worked for me in Python 2.7

Upvotes: 0

Related Questions