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
itemsas a single argument toadd, which is written to expect an arbitrary number of individual numeric arguments rather than a single iterable argument (that's what the*argssyntax does -- it takes an artitrary number of arguments and converts them to an iterable inside the function).The
TypeErroris happening because yourfor x in argsis getting the value ofitemsas its first value ofx(since it's the first argument), and so your function is trying to do the operation0 + (5, 7, 4, 12), which is not valid because you can't add anintto atuple(which is why the error message says that).To pass the individual items as individual args, do:
or unpack the tuple by mirroring the
*syntax in the caller, like this:Note that Python has a builtin function called
sumthat will do exactly what you want to do with your tuple:You could get the same behavior from your
addfunction by removing the*from the*argsin your function definition.