0

My understanding is that *args can be used to allow an arbitrary number of inputs in a Python function. For example, the function

def f(*x):
    for v in x:
      print(v)

could be called as

f(1)
# or
f(1, 2, 3)

However, it seems to me that this is equivalent to defining a function that takes a list of values as an argument. For example, we could define the same function as

def f(x):
    for v in x:
      print(v)

and call it as

f([1])
# or
f([1, 2, 3])

and this would result in the same behavior.

Given this, why should we use the * pattern in defining functions instead of passing lists? Is it more "correct"? Faster? More secure? Or are there use cases where only the * pattern achieves the desired outcome?

book_kees
  • 307
  • 1
  • 9
  • ...and what about `**kwargs`? – Anentropic May 27 '22 at 14:51
  • The particular use case of `**kwargs` seems straightforward, as this can be used to unpack a dictionary to feed keyword arguments, and I'm not sure there's another easy way to do that (described here for example: https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters). I was confused because the `*args` construction seems unnecessary – book_kees May 27 '22 at 14:58
  • I dont think `*args*` is faster at all, I think its only there for convenience. In cases you would like to call it like `f(1, 2, 3)` instead of `f([1, 2, 3])` as you mentioned. Its technically two less characters that way. – rv.kvetch May 27 '22 at 15:05
  • 2
    @book_kees they both have uses in things like decorators and sub-classes, where you may want to capture an arbitrary and/or unknown number of positional and keyword arguments and pass them through in a call to a function or method which may accept them as discrete named args i.e. so that the signature of your function is compatible with the other one – Anentropic May 27 '22 at 15:17
  • you don't always know the amount of arguments of a callable object – cards May 27 '22 at 15:30
  • Does this answer your question? [Why use packed \*args/\*\*kwargs instead of passing list/dict?](https://stackoverflow.com/questions/33542959/why-use-packed-args-kwargs-instead-of-passing-list-dict) – Andre Dilay Jun 20 '22 at 15:46

0 Answers0