A Quick Guide on *args & **kwargs in Python

*args and **kwargs in Python

Arastoo
Arastoo
Jun 11 · 2 min read

*args in Python

Assuming that you want to make a function to calculate the multiple of some inputs. The simple way to do this is using a def statement with two arguments.

def mul(x, y):
    return x * yprint(mul(10, 5))

But what will happen if I enter more or less than 2 inputs in the mul function? It’s not a big deal we just get an error!

So how can I set the inputs of a function in a very flexible amount? There’s where *args came.

With the *args argument you can tell python to be ready for accepting an unknown number of inputs. Let’s look at an example:

def mul(*args):
    return argsprint(mul(10,20,30,40))

If you run this snippet you can see there’s a tuple. So *args will return a tuple of all the inputs that we put in the function.

Now I can iterate on my tuple and use their data to make my multiple function.

def mul(*args):
    res = 1
    for num in args:
        res = res*num    return resprint(mul(10,20))
print(mul(10,20,30))
print(mul(10,20,30,40))

**kwargs in Python

Now, the difference between *args in **kwargs is that **kwargs return the inputs in a dictionary form. Surely the inputs must be in a dictionary way, too. Otherwise, there will be an error.

def info(**kwargs):
    return kwargsprint(info(‘Arastoo’, ‘Web Development))

Error:

TypeError: info() takes 0 positional arguments but 2 were given

The error says to us that info() function just take keyword arguments but you entered 2 positional arguments. So you must enter your inputs in a key=value way.

def info(**kwargs):
    return kwargsprint(info(name = ‘Arastoo’, career= ‘Web Development))

Now you can see that there’s a dictionary, if you wanna be sure make a type of it.

For iterating on a dictionary you can

def info(**kwargs):
    for key, value in kwargs.items():
        print(f’{key}: {value}’)
info(name = ‘Arastoo’, career= ‘Web Developer’)

2

2 claps
Arastoo

Written by

Arastoo

Writer, Blogger, Instructor, Full-Stack Developer