I'm getting a TypeError while using a tuple in a multiple arguments function. Here's my code:
def add(*args):
result = 0
for x in args:
result = result + x
return result
items = 5, 7, 4, 12
total = add(items)
print(total)
This is the error:
Traceback (most recent call last):
File "e:\functions.py", line 9, in <module>
total = add(items)
File "e:\functions.py", line 4, in add
result = result + x
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
I'm not getting any error if I directly enter the arguments instead of using a variable:
total = add(5, 7, 4, 12)
I've coded in Java and I just started using Python and I can't figure out why this is happening.
You're passing the tuple items
as a single argument to add
, which is written to expect an arbitrary number of individual numeric arguments rather than a single iterable argument (that's what the *args
syntax does -- it takes an artitrary number of arguments and converts them to an iterable inside the function).
The TypeError
is happening because your for x in args
is getting the value of items
as its first value of x
(since it's the first argument), and so your function is trying to do the operation 0 + (5, 7, 4, 12)
, which is not valid because you can't add an int
to a tuple
(which is why the error message says that).
To pass the individual items as individual args, do:
total = add(5, 7, 4, 12)
or unpack the tuple by mirroring the *
syntax in the caller, like this:
total = add(*items)
Note that Python has a builtin function called sum
that will do exactly what you want to do with your tuple:
total = sum(items)
You could get the same behavior from your add
function by removing the *
from the *args
in your function definition.