2

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)
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

3 Answers3

5

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
pault
  • 41,343
  • 15
  • 107
  • 149
2

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

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

ddor254
  • 1,570
  • 1
  • 12
  • 28
  • 1
    The order of the arguments matter. `f(3, *a)` is **not** the same as `f(*(a + (3,)))` – pault Dec 18 '18 at 15:01
  • 3
    Syntactically, it works, but in general positional arguments have to be passed in an expected order. – chepner Dec 18 '18 at 15:01
  • the order does matter so this will not help me, but its cool to see this works! UV – CIsForCookies Dec 18 '18 at 15:02
  • i know that for the OP the order matters - if you really want to call the function without new tuple , order in function declaration can be changed accordingly ,:) – ddor254 Dec 18 '18 at 15:03