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)
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)
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])
In [7]:
print("But when your list is too long/short...")
function3(*[1,2,3])
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})
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})
In [ ]: