Can a variable number of arguments be passed to a function?


Question

In a similar way to using varargs in C or C++:

fn(a, b)
fn(a, b, c, d, ...)
1
320
4/18/2015 8:57:13 PM

Accepted Answer

Yes.

This is simple and works if you disregard keyword arguments:

def manyArgs(*arg):
  print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2,3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will give you a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

413
5/23/2017 12:26:27 PM

Adding to unwinds post:

You can send multiple key-value args too.

def myfunc(**kwargs):
    # kwargs is a dictionary.
    for k,v in kwargs.iteritems():
         print "%s = %s" % (k, v)

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

And you can mix the two:

def myfunc2(*args, **kwargs):
   for a in args:
       print a
   for k,v in kwargs.iteritems():
       print "%s = %s" % (k, v)

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon