Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a python function that adds all arguments?

I'd like to write a python function which adds all its arguments, using + operator. Number of arguments are not specified:

def my_func(*args):
    return arg1 + arg2 + arg3 + ...

How do I do it?

Best Regards

like image 703
alwbtc Avatar asked Jul 17 '12 10:07

alwbtc


1 Answers

Just use the sum built-in function

>>> def my_func(*args):
...     return sum(args)
...
>>> my_func(1,2,3,4)
10
>>>

Edit:

I don't know why you want to avoid sum, but here we go:

>>> def my_func(*args):
...   return reduce((lambda x, y: x + y), args)
...
>>> my_func(1,2,3,4)
10
>>>

Instead of the lambda you could also use operator.add.


Edit2:

I had a look at your other questions, and it seems your problem is using sum as the key parameter for max when using a custom class. I answered your question and provided a way to use your class with sum in my answer.

like image 78
sloth Avatar answered Nov 26 '22 07:11

sloth