1

I am supposed to use find out how to use "*" to sum up several values. For example:

sum_all(1, 2, 3, 4, 5)  
15
sum_all(49, 51)  
100

Given a general function like :

def sum_all(*args)

I am unsure how to implement the * within the code.

3
  • 1
    *args is a list, **kwargs a dictionary. Just proceed as you would with any of them. Commented Mar 28, 2014 at 10:42
  • @ikaros45: Technically it's a tuple since it doesn't support item assignment. Commented Mar 28, 2014 at 11:19
  • @SanjayT.Sharma: Sir, you are damn right. Commented Mar 28, 2014 at 11:59

6 Answers 6

3
def sum_all(*args):
    total = 0
    for arg in args:
        total += sum(arg)
    return total

To be different from the others which i think posted at the same time as me, i'll explain and come up with another solution.

When doing *args you can look at it this way:

def sum_all([arg1, arg2, arg3, ...]):

Which would tedious to code and since you don't know how many parameters are given, you do *args instead, which dynamically takes a "endless" amount of arguments in a list format.

The most neat way i can think of:

def sum_all(*args):
    return sum(sum(arg) for arg in args)

This assumes the input is something along the lines of:

sum_all([1,2,3], [5,5], [10,10])

If not just skip one of the sums:

def sum_all(*args):
    return sum(args)
Sign up to request clarification or add additional context in comments.

3 Comments

sum(arg for arg in args) is just an verboser and way more innefficient version of just sum(args)
@ikaros45 yepp, i'm aware.. but m.wasowski beat me to it so didn't feel like changing the answer, but i will
One question for the last code: when you use def sum_all(*args): return sum(args), why could you use args without the *?
2

You can treat the passed in variable as an iterable.

sum_nums = 0
for val in args:
    sum_nums += val

A good read would be the top answer in this question.

Comments

2
def sum_all(*args):
    s = 0
    for n in args:
       s = s + n
    return s

Comments

1

In short:

def sum_all(*args):
    return sum(args)

*args represent here a sequence of positional arguments, that you can later iterate over. Fortunately, builtin sum() takes single iterable as argument, so you can just pass it there.

More info you can find in docs: http://docs.python.org/2/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another

Comments

1

Just 2 lines of code :)

def sum_all(*args):
    return (sum(args[0])

Comments

1

You can try as,

 def sum_all(*args):
    return sum([i for i in args])

Comments

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.