Specify an arbitrary argument in addition to *args in python

46 views Asked by At

For a function with multiple arguments like this:

def f(a, b, c):
    return a + b + c

it is straightforward to define a new function as follows:

def g(a, *args):
    return f(a, *args)

here, a is the first argument of f(). What if I would like to specify the second argument of f(), namely:

def g(b, *args):
    # return f(???)
2

There are 2 answers

0
quamrana On BEST ANSWER

You can unpack some of the arguments from *args:

def f(a, b, c):
    return a + b + c


def g(b, *args):
    a,*rest = args
    return f(a, b, *rest)


print(g(1,2,3))

Output:

6

0
James On

You are just reordering the args in you last example such that b is the the first named args. However, you will need to unpack *args to get a and c before passing them to f.

def g(b, *args):
    a, c = args
    return f(a, b, c)