0

I would like to create a function of n variables in python, such as

n=3
def func(n1,n2,n3):
    return sum(n1+n2+n3)

func(1,2,3) = 6
func(3,3,3)=9

or if n=4,

n=4
def func(n1,n2,n3,n4):
    return sum(n1+n2+n3+n4)

func(1,2,3,4) = 10

There is a perfect example of someone doing this in julia: How to create a function of n variables (Julia)

using this solution

function f(x...)
     sum(x)
end

julia> f(1,2,3)
6

However I do not know how to translate the ellipses type input to python

valerio
  • 3
  • 1

2 Answers2

1

Python supports variable arguments too

def f(*x):
    return sum(x)

The x inside the function will also be a tuple, like in Julia.

Julia:

julia> function f(x...)
        x
       end

f (generic function with 1 method)

julia> f(2,4,5)
(2, 4, 5)

Python:

>>> def f(*x):
...  return x
... 
>>> f(2,4,5)
(2, 4, 5)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

Use unpacking operator (*):

def func(*x):
    return sum(x)

Note that when using this notation x is tuple inside func, which sum happilly accepts.

Daweo
  • 31,313
  • 3
  • 12
  • 25