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


While creating a function the single asterisk (*) defined to accept and allow users to pass any number of positional arguments. And in the same way the double asterisk (**) defined to accept any number of keyword arguments.

The single asterisk (*) can be used when we are not sure how many arguments are going to be passed to a function and those arguments that are not keywords.

The double asterisk (**kwargs) can be used to pass keywords, when we don't know how many keyword arguments will be passed to a function, which will be in a dict named kwargs.

While defining a function

Let’s create a Python function which can accept an arbitrary number of positional arguments.

Example

Create a python function which can accept an arbitrary number of positional arguments.

def function(*args):
    result = 0
    for ele in args:
        result+=ele
    return result

print(function(1,2,3,4,5,6,7))
print(function(10,10,10)) 
print(function(1))

Output

28
30
1

Example

Let’s see how the double star operator will create a Python with an arbitrary number of keyword arguments.

def function(**args):
    result = 0
    for k, v in args.items():
        result+=v
    return result

print(function(a=1,b=2,c=3,d=4))
print(function(i=10,j=100)) 

Output

10
110

The above function is created to pass any number of keyword arguments, if we call the function without mentioning the keywords function(10,100) then it will raise the TypeError.

Unpacking the iterables

Another way of using asterisk operators as a parameter is to unpack the argument iterables when calling a function.

Example

Here we can see that the single asterisk '*' operator used to unpack data structures like list or tuple into arguments.

def sample_function(a, b, c):
    print(a, b, c)

l = [1, 2, 3]

sample_function(*l)

Output

1 2 3

Example

The above following example explains that the double asterisk '**' operator unpacks a dictionary into keyword arguments.

def sample_foo(a, b):
    return 'a({}) + b({}) = {}'.format(a,b,a+b)

d = {'b': 100, 'a':10}

print(sample_foo(**d))

Output

a(10) + b(100) = 110

Updated on: 09-Sep-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements