380

Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook:

def get(self, *a, **kw)

Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Martin08
  • 20,990
  • 22
  • 84
  • 93
  • 2
    See also https://stackoverflow.com/questions/14301967/bare-asterisk-in-function-arguments for a bare asterisk – naught101 Dec 13 '18 at 03:44
  • Is this still a duplicate? The referenced question is specifically about parameters to functions, while this question (at least from its title) would also cover syntax like `[*my_dict]` – dumbledad Mar 13 '20 at 11:46

5 Answers5

355

See Function Definitions in the Language Reference.

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

Also, see Function Calls.

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa
b = testb
c = testc
('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

def foo(a,b,c,**args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

Prints:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

And

def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

Prints:

a=testa
b=testb
c=testc
args=('excess',)
Pavel
  • 1
  • 3
  • 17
  • 51
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 254
    Whilst this is a very precise definition, it is a very bad explanation; and highly unlikely to actually help a struggling programmer. – LittleBobbyTables Aug 02 '13 at 21:29
  • 2
    The links to the documentation are broken. – reasgt Mar 26 '14 at 18:28
  • What does the asterisk mean when there is no argument name? For example in some functions of the class [pprint](https://docs.python.org/3/library/pprint.html). – Ziyuan Apr 14 '15 at 12:24
  • 1
    It separates regular parameters from keyword-only parameters. From the doc index page for '*': https://docs.python.org/dev/reference/compound_stmts.html#index-22 – merwok Oct 30 '15 at 23:40
  • Yeah. Explain what a tuple and a dictionary is. – Jossie Calderon Jun 15 '16 at 13:55
  • What are excess keyword arguments? Can I have an example? – Pavel Dec 06 '16 at 14:01
  • 16
    I find this explanation very enlightening. The commenter stated clearly "Assuming that one knows what positional and keyword arguments are." So he did a very great job. It is good explanation by all standards – chidimo Dec 31 '16 at 22:06
  • Compare with the legacy/heritage C usage of **argv (equivalent to *argv[]) which is a pointer to a 'collection' of pointers to char (being strings). Other languages call this a stringlist or a collection. Another reason why C needs to be taught before Python. Many admins put backdoors (well back) in the excess args of this example, but that's a bit hard if Python source is exposed to all and sundry. – mckenzm May 02 '19 at 05:42
206

I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

You may also use the stars when calling the function. For example, say you have code like this:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}
Jason Baker
  • 192,085
  • 135
  • 376
  • 510
  • 13
    Sorry to bring this up 7 years later, but if you removed `**` from the fn declaration to just have `def foo(argd):` and you ran `foo(d)` you would get the same result. Why then are `**` used? – David Oct 09 '15 at 23:42
  • 5
    @David yes, you're right. The example is just to demonstrate how to "unpack" a dict and then "repack" it inside the function. For example, `foo(a="b", c="d")` would also provide the same output as `foo(**d)`. – laughingbovine Dec 02 '15 at 18:04
  • 3
    I saw the first answer and I was like , "Noo, this is not what I wanted", and then I saw your answer :) – abhayAndPoorvisDad Feb 07 '17 at 10:06
  • 2
    For clarity, this example is using `*` for unpacking a sequence (such as a list) when passed as an argument to a function that uses `*args` for an arbitrary number of positional arguments. – howdoicode Sep 26 '20 at 18:55
100

All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.

They are called the argument-unpacking and keyword-argument-unpacking operators.

Salim Fadhley
  • 22,020
  • 23
  • 75
  • 102
41

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...
tzot
  • 92,761
  • 29
  • 141
  • 204
HUAGHAGUAH
  • 1,063
  • 6
  • 3
32

I find * useful when writing a function that takes another callback function as a parameter:

def some_function(parm1, parm2, callback, *callback_args):
    a = 1
    b = 2
    ...
    callback(a, b, *callback_args)
    ...

That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:

def my_callback_function(a, b, x, y, z):
    ...

x = 5
y = 6
z = 7

some_function('parm1', 'parm2', my_callback_function, x, y, z)

Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().

Clint Miller
  • 15,173
  • 4
  • 37
  • 39