Tarun Maganti
Tarun Maganti

Reputation: 3086

How to combine variable length arguments with keyword arguments in python?

def addv(a,b,*args):
    sum = a + b
    for x in args:
        sum += x
    return sum

addv(b = 1,a = 2) # This is valid
addv(args = (1,2,3,4,5,6,7,8),b = 9, a = 10) #This is giving me unexpected keyword argument.

I learned that keyword arguments are essentially passed as tuples. So, in an attempt to combine both keyword and variable arguments, I did the above experiment.

Is there any way to do such a kind of thing or all variable arguments must be passed to the end while calling a function.

Upvotes: 1

Views: 3279

Answers (1)

Omar Einea
Omar Einea

Reputation: 2524

You should use the ** operator to catch key word arguments. like this:

def addv(*args, **kwargs):
    result = 0
    for x in args:
        result += x
    for x in kwargs.values():
        result += x
    return result

Or a shorter way (suggested by Delirious Lettuce):

def addv(*args, **kwargs):
    return sum(args) + sum(kwargs.values())

Now you can do this:

addv(b = 1, a = 2) # Outputs: 3
addv(1, 2, 3, 4, 5, 6, 7, 8, b = 9, a = 10) # Outputs: 55

Upvotes: 5

Related Questions