Benefits of using * args in python instead of passing as a parameter
In general, it either passed a list of arguments to a function, which usually took a fixed number of arguments, or in function definitions that allowed a variable number of arguments to be passed in the style of regular arguments. For example, the function print()
uses varargs so you can do things like print(a,b,c)
.
One example from a recent SO question: you can use it to pass a list of lists of results range()
in itertools.product()
without having to know the length of list-of-lists.
Of course, you can write every library function to look like this:
def libfunc1(arglist):
arg1 = arglist[1]
arg2 = arglist[2]
...
... but it wins in that he named the positional argument variables, it basically means what *args
it does for you, and that leads to redundant parentheses / parens since you need to call a function like this:
libfunc1([arg1val,arg2val,...])
... which looks a lot like ...
libfunc1(arg1val,arg2val,...)
... except for unnecessary characters as opposed to using *args
.
a source to share
This means flexibility .
This allows you to pass arguments without knowing how many you need. Typical example:
def f(some, args, here): # <- this function might accept a varying nb of args
...
def run_f(args, *f_args):
do_something(args)
# run f with whatever arguments were given:
f(*f_args)
Be sure to check your keyword version **
.
a source to share