142

What do the * and ** mean in this code?

def functionA(self, *a, **kw):
   # code here
1

3 Answers 3

309

Inside a function header:

* collects all the positional arguments in a tuple.

** collects all the keyword arguments in a dictionary.

>>> def functionA(*a, **kw):
       print(a)
       print(kw)


>>> functionA(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)
(1, 2, 3, 4, 5, 6)
{'a': 2, 'c': 5, 'b': 3}

In a function call:

* unpacks a list or tuple into position arguments.

** unpacks a dictionary into keyword arguments.

>>> lis=[1, 2, 3, 4]
>>> dic={'a': 10, 'b':20}
>>> functionA(*lis, **dic)  #it is similar to functionA(1, 2, 3, 4, a=10, b=20)
(1, 2, 3, 4)
{'a': 10, 'b': 20}
1
  • 2
    Interesting functionality, clearly explained.. Can understand the code now, might one day find a use for it in my own code. For a clear explanation of positional vs keyword arguments see also this answer
    – cardamom
    Commented Aug 3, 2017 at 11:30
13

** takes specified argument names and puts them into a dictionary. So:

def func(**stuff):
    print(stuff)

func(one = 1, two = 2)

Would print:

{'one': 1, 'two': 2}
0
12

** means named arguments of the functions.

$ cat 2.py
def k(**argv):
    print argv

k(a=10, b = 20)

$ python 2.py
{'a': 10, 'b': 20}

argv is a dictionary that contains all named arguments of the function.

And you can also reverse it. You can use a dictionary as a set of aruments for a function:

def k(a=10, b=20):
  print a
  print b

d={'a':30,'b':40}
k(**d)

would print

30
40

Not the answer you're looking for? Browse other questions tagged or ask your own question.