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
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
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.
sum
function. –
Ernestoernestus +
operator for cases other than numbers. –
Semeiology __radd__
method to his class. –
Alms How about this:
def my_func(*args):
my_sum = 0
for i in args:
my_sum += i
return my_sum
If you don't want to use the +=
operator, then
my_sum = my_sum + i
sum()
by replacing my_sum = 0
with my_sum = args[0]
and the loop to be for i in args[1:]
. This now works on any list of objects with a sensible __add__
method. –
Semeiology __radd__
method in your class. –
Alms If you definitely won't be using sum
, then something like:
def func(*args, default=None):
from operator import add
try:
return reduce(add, args)
except TypeError as e:
return default
or functools.reduce
in Py3
def sumall(*args):
sum_ = 0
for num in args:
sum_ += num
return sum_
print(sumall(1,5,7))
The output is 13
.
© 2022 - 2024 — McMap. All rights reserved.
*args
thenargs
is a list of all arguments passed. – Sodomsum
? That's precisely what it does. – Heidtsum
in the first place. – Alms