on asterisks in Python

Asterisks have lots of meaning in Python. Firstly, consider in a function definition

>>> def function(arg, *vargs, **kargs):
    print arg
    print vargs
    print kargs
>>> function(1, 2,3,4,5, test1="abc", test2="def")
(2, 3, 4, 5)
{'test1': 'abc', 'test2': 'def'}
  • *vargs puts all left-over non-keyword arguments into a tuple called vargs.
  • **kargs puts all left-over keyword arguments into a dictionary called kargs.

On the other hand, you can use the asterisk with a tuple when calling a function to expand out the elements of the tuple into positional arguments

>>> def function(arg1, arg2, arg3):
    print arg1, arg2, arg3
>>> args = (1,2,3)
>>> function(*args)
1 2 3

You can do a similar thing with keyword arguments and a dictionary with the double asterisk operator

>>> def function(arg1=None, arg2=None):
     print arg1, arg2
>>> dict = {"arg1":"1", "arg2":"2"}
>>> function(**dict)
1 2