1
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.

2
  • Your first example doesn't seem valid since the positional arguments follow keyword arguments. Commented Mar 3, 2018 at 6:31
  • Yes. I just corrected it. Thanks. Commented Mar 3, 2018 at 6:33

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

sum as a variable name?
@DeliriousLettuce oh, that's what you mean, I just copied the OP's code not noticing that xD
Instead of saying "you are kidding", why not just say: "it's bad practice to overshadow built-in variable names"?
No problem! I just meant that you could simplify it like this if you use sum properly. return sum(args) + sum(kwargs.values())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.