Computer >> Computer tutorials >  >> Programming >> Python

What does ** (double star) and * (star) do for parameters in Python?


In Python function, an argument with single asterisk (star) prefixed to it helps in receiving variable number of argument from calling environment

>>> def function(*arg):
      for i in arg:
        print (i)

>>> function(1,2,3,4,5)
1
2
3
4
5

Argument with double asterisks (stars) is used in function definition when variable number of keyword arguments have to be passed to a function

>>> def function(**arg):
      for i in arg:
        print (i,arg[i])


>>> function(a=1, b=2, c=3, d=4)
a 1
b 2
c 3
d 4

In Python 3, it is possible to define a variable with asterisk in assignment statement to enable extended unpacking of iterables.

>>> a,*b=[1,2,3,4]
>>> a
1
>>> b
[2, 3, 4]
>>> a,*b,c=[1,2,3,4]
>>> a
1
>>> b
[2, 3]
>>> c
4