Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using *args when a list of arguments can be used?

Tags:

python

Would passing in a list or dictionary of variables be more concise than passing in *args in Python methods?

For example,

def function(a, *argv):
   print('First variable:', a)
   for k in argv:
      print('Additional variable:',k)

is the same as

def function(a, list):
   print('First variable:', a)
   for k in list:
      print('Additional variable:',k)

except a list is passed in the second argument. What I think using *args would often do is to cause additional bugs in the program because the argument length only needs to be longer than the mandatory argument length. Would any please explain situations where *args would be really helpful? Thanks

like image 961
James Fang Avatar asked Dec 22 '22 22:12

James Fang


1 Answers

The first function accepts:

function('hello', 'I', 'am', 'a', 'function')

The second one won't. For the second you'd need:

function('hello', ['I', 'am', 'a', 'function'])

In principle, the first one is used when your function can have an arbitrary number of parameters (think: print), while the second one specifies that there's always a second parameter, which is an iterable (not necessarily a list, despite the name)

like image 182
GPhilo Avatar answered Jun 04 '23 06:06

GPhilo