Advantages Of Using *args In Python Instead Of Passing A List As A Parameter
Solution 1:
Generally it's used to either pass a list of arguments to a function that would normally take a fixed number of arguments, or in function definitions to allow a variable number of arguments to be passed in the style of normal arguments. For instance, the print()
function uses varargs so that 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 range()
result lists to itertools.product()
without having to know the length of the list-of-lists.
Sure, you could write every library function to look like this:
def libfunc1(arglist):
arg1 = arglist[1]
arg2 = arglist[2]
...
...but that defeats the point of having named positional argument variables, it's basically exactly what *args
does for you, and it results in redundant braces/parens, since you'd have to call a function like this:
libfunc1([arg1val,arg2val,...])
...which looks very similar to...
libfunc1(arg1val,arg2val,...)
...except with unnecessary characters, as opposed to using *args
.
Solution 2:
That is for flexibility.
It allows you to pass on the arguments, without knowing how much you need. A typical example:
deff(some, args, here): # <- this function might accept a varying nb of args
...
defrun_f(args, *f_args):
do_something(args)
# run f with whatever arguments were given:
f(*f_args)
Make sure to check out the **
keyword version.
Post a Comment for "Advantages Of Using *args In Python Instead Of Passing A List As A Parameter"