I have an function that takes an array as an input. How can I modify it to work with variable arguments as well as arrays. For example I want arrSum(1,2,3) == arrSum([1,2,3])
to return True
i.e. both should return 6
I have already asked this same question for JavaScript but when I tried to implement the same technique in Python I am getting totally unexpected errors.
This is what I have tried to do based on my current knowledge of python.
def arrSum(*args):
listOfArgs = []
listOfArgs.extend([*list(args)])
return sum(listOfArgs)
It works perfectly for arrSum(1,2,3)
but returns error for arrSum([1,2,3])
arrSum(1,2,3)
returns 6
which is the expected output.
But `arrSum([1,2,3]) returns the following error:
Traceback (most recent call last):
File "python", line 7, in <module>
File "python", line 4, in arrSum
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Doing a print(listOfArgs)
before return sum(listOfArgs)
prints [[1,2,3]]
.
REPL.it link of the function