405

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).

2
  • 3
    See also stackoverflow.com/questions/14301967/… for a bare asterisk Commented Dec 13, 2018 at 3: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] Commented Mar 13, 2020 at 11:46

5 Answers 5

387

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 3) 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 3) 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',)
Sign up to request clarification or add additional context in comments.

8 Comments

Whilst this is a very precise definition, it is a very bad explanation; and highly unlikely to actually help a struggling programmer.
The links to the documentation are broken.
What does the asterisk mean when there is no argument name? For example in some functions of the class pprint.
It separates regular parameters from keyword-only parameters. From the doc index page for '*': docs.python.org/dev/reference/compound_stmts.html#index-22
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
|
211

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'}

5 Comments

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 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).
I saw the first answer and I was like , "Noo, this is not what I wanted", and then I saw your answer :)
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.
@howtocode No, * is actually unpacking the arguments - no need for *args in the function definition. The same goes for **params. To others, to clarify, it unpacks both positional and named arguments from a list, respectively. So :david, your example only works because one argument is unpacked into one argument.
107

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.

Comments

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...

Comments

34

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.