Benefits of using * args in python instead of passing as a parameter

I'm going through python and I was wondering what are the benefits of using * args as a parameter just to pass a list as a parameter, besides aesthetics?

+2


a source to share


2 answers


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

.

+2


a source


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 **

.

+2


a source







All Articles