Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arbitrary number of arguments in a python function

Tags:

python

I'd like to learn how to pass an arbitrary number of args in a python function, so I wrote a simple sum function in a recursive way as follows:

def mySum(*args):
  if len(args) == 1:
    return args[0]
  else:
    return args[-1] + mySum(args[:-1])

but when I tested mySum(3, 4), I got this error:

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Does anyone have an idea about this and gimme some clue to correct it?

like image 790
wei Avatar asked Oct 29 '12 16:10

wei


2 Answers

This line:

return args[-1] + mySum(args[:-1])

args[:-1] returns a slice of the arguments tuple. I assume your goal is to recursively call your function using that slice of the arguments. Unfortunately, your current code simply calls your function using a single object - the slice itself.

What you want to do instead is to call with those args unrolled.

return args[-1] + mySum(*args[:-1])
                        ^---- note the asterisk

This technique is called "unpacking argument lists," and the asterisk is sometimes (informally) called the "splat" operator.

like image 149
voithos Avatar answered Oct 22 '22 09:10

voithos


If you don't want to do it recursively:

def mySum(*args):
    sum = 0
    for i in args:
        sum = sum + i
    return sum
like image 37
schrobe Avatar answered Oct 22 '22 11:10

schrobe