Main Content

vargs in Python - how to call a method with unknown number of parameters

Archive - Originally posted on "The Horse's Mouth" - 2012-12-06 07:12:17 - Graham Ellis

In C, a few functions such as printf can take a variable number of arguments, and it's possible (but not common) for you to write functions like that too. In Python, though, it's much more common. In declaring a function, you can specify:
  a) Mandatory parameters, just with a name
  b) Optional parameters, with the name=defaultvalue syntax
  c) A list name to collect all remaining unnamed parameters, using *name
  d) A dict name to collect all named parmeters, using **name

Here's the equivalent of printf (in calling terms) - a function that picks up as few or as many unnamed parameters as it's passed:

  def walter(*kids):
    for kid in kids:
      print "Clean behind the ears of",kid


and here's the ultimately flexible function, picking up as few or as many named parameters as it's given:

  def gabriel(*mylist, **mydict):
    for posn in range(len(mylist)):
      print posn,"-",mylist[posn]
    for k in mydict.keys():
      print k,":",mydict[k]


Complete example (showing calls and how it runs too) from yesterday's Python Course is [here].