1.

What is the special significance of * and ** in Python?

Answer»

In Python, single and double asterisk (* and **) SYMBOLS are defined as multiplication and exponentiation operators respectively. However, when prefixed to a variable, these symbols carry a special meaning. Let us see what that means.

A Python function is defined to receive a certain number of arguments. Naturally the same number of arguments must be provided while calling the function, otherwise Python interpreter raises TypeError as shown below.

>>> def add(x,y): RETURN x+y >>> add(11,22) 33 >>> add(1,2,3) Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    add(1,2,3) TypeError: add() takes 2 positional arguments but 3 were given

This is where the use of formal argument prefixed with single * comes. In a function definition, an argument prefixed with * is able to receive variable number of VALUES from the calling environment and stores the values in a tuple object.

>>> def add(*numbers): s=0 for n in numbers: s=s+n return s >>> add(11,22) 33 >>> add(1,2,3) 6 >>> add(10) 10 >>> add() 0

Python allows a function to be called by using the formal arguments as keywords. In such a CASE, the order of argument definition need not be followed.

>>> def add(x,y): return x+y >>> add(y=10,x=20) 30

However, if you want to define a function which should be able to receive variable number of keyword arguments, the argument is prefixed by ** and it stores the keyword: values passed as a dictionary.

>>> def add(**numbers): s=0 for k,v in numbers.items(): s=s+v return s >>> add(a=1,b=2,c=3,d=4) 10

In fact, a function can have positional arguments, variable number of arguments, keyword arguments with defaults and variable number of keyword arguments. In order to use both variable arguments and variable keyword arguments, **variable should appear last in the argument list.

>>> def add(x,y,*arg, **kwarg): print (x,y) print (arg) print (kwarg) >>> add(1,2,3,4,5,6,a=10,b=20,c=30) 1 2 (3, 4, 5, 6) {'a': 10, 'b': 20, 'c': 30}


Discussion

No Comment Found