I am new to Python and just learned function and variable length arguments.
I am trying to write a function that takes any number of arguments, and sums all numeric types, in consideration of the argument could be any type, including a list of a list of a list.
The following code is what I came up with so far:
def sum_all(*args):
if len(args) == 0:
return None
ls = list(args)
sum = 0
for elem in ls:
if isinstance(elem, (list, tuple)):
for i in elem:
ls.append(i)
elif isinstance(elem, (int, float)):
sum += elem
return sum
When I call the function as followed:
test1 = [1, 3, 5, 7, 9]
test2 = [1, 2, [3, 4], 5, 6, 7, [8, 9]]
test3 = [[1, 2, "string", {"error": 404}, [3, [4, 5]]], 6, 7, [8, [9, [10, 11]]], (12, 13, 14)]
print(sum_all(test1))
print(sum_all(test2))
print(sum_all(test3))
It returns the result as expected:
25
45
105
It works fine, but it basically just appends everything to the end of the original list, intuitively speaking, it should be inefficient.
I understand the saying - "if the code works, don't touch it" - but is there a way to make it more elegant?
If it is not too much to ask, please provide one without importing modules and one with (if there is one).