What do * (single star or asterisk) and ** (double star or asterisks) mean?

Both * and ** have several distinct uses in Python. The first - and perhaps the most common - is to allow you to pass an arbitrary number of arguments to a function. In other words, you use * and ** in this way when you are defining the function:

In [1]:
def function1(*args): 
    print(args)
In [2]:
print("Calling function1 with just one argument:")
function1(1)
print("And calling it with three arguments:")
function1(1,'a',10)
Calling function1 with just one argument:
(1,)
And calling it with three arguments:
(1, 'a', 10)

So the single star * returns a tuple... and the double star ** returns a dictionary:

In [3]:
def function2(**kwargs):
    print(kwargs)
In [4]:
print("Calling function2 with arbitrary inputs:")
function2(test1=1, test2=2)
Calling function2 with arbitrary inputs:
{'test2': 2, 'test1': 1}

Alternatively you can use the stars to input lists/dictionaries when the function would normally take plain, boring, single variables:

In [5]:
def function3(x,y):
    print(x,y)
In [6]:
print("Inputting one list to a function that takes two variables:")
function3(*[1,2])
Inputting one list to a function that takes two variables:
1 2
In [7]:
print("But when your list is too long/short...")
function3(*[1,2,3])
But when your list is too long/short...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-f9b17dc6512e> in <module>()
      1 print("But when your list is too long/short...")
----> 2 function3(*[1,2,3])

TypeError: function3() takes 2 positional arguments but 3 were given

Rather predictably, you can use a dictionary to pass in a number of keyword arguments in one go with **:

In [8]:
def function4(x=3, y=4):
    print(x,y)
In [9]:
print("With no input:")
function4()
print("With a dict input and some asterisks:")
function4(**{'x':1, 'y':2})
With no input:
3 4
With a dict input and some asterisks:
1 2

But be careful - the dictionary keys must match the keyword arguments:

In [10]:
print("With bad keys in the dictionary:")
function4(**{'a':1, 'b':2})
With bad keys in the dictionary:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-9e90825a8f89> in <module>()
      1 print("With bad keys in the dictionary:")
----> 2 function4(**{'a':1, 'b':2})

TypeError: function4() got an unexpected keyword argument 'b'
In [ ]:
 

blogroll

social