Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional arguments function

Tags:

python

I am searching how I could use optional arguments in python. I have read this question but it is not clear to me. Lets say I have a function f that can take 1 or more arguments to understand time series. Am i obliged to specify the number of arguments and set default values for each argument? What I aim to do is being able to write a function this way:

simple function:

def f(x,y):
    return x + y
#f(1,2) returns 3

What i want is also f(1,2,3) to return me 6 and f(7) returning me 7

Is it possible to write it without setting a predefined number of mandatory/optional parameters? Is it possible to write it without having to set default values to 0 ? How to write this function?

Its a simple example with numbers but the function i need to write is comparing a set of successive objects. After comparison is done, the data set will feed a neural network.

Thanks for reading.

EDIT: Objects I am feeding my function with are tuples like this (float,float,float,bool,string)


1 Answers

You can put *args in your function and then take arbitrary (non-keyword) arguments. *args is a tuple, so you can iterate over it like any Python tuple/list/iterable. IE:

def f(*args):
    theSum = 0
    for arg in args:
        theSum += arg
    return theSum

print f(1,2,3,4)
like image 182
Doug T. Avatar answered May 22 '26 11:05

Doug T.