To understand python *args and **kwargs first, we need to know some common problems we face while programming in python and how *args and **kwargs solve them?
Examine the following python code:
1 2 3 4 5 6 7 8 9 | def add(a, b): return a+b print(add(5,6)) def add(a, b, c, d, e, f): return a+b+c+d+e+f print(add(5,6,1,5,2,2)) |
Output
1 2 | 11 21 |
Notice that we have to write a separate function for adding the different number of arguments. We can simplify this by using a list and sum method.
1 2 3 4 | def add(lst): return sum(lst) print(add([5,6,1,5,2,2])) |
Output
1 | 21 |
The little burden of using a list, but still we can do it in a more simple way using *args.
What is *args in Python?
*args is a Non-Keyword Argument which can accept the variable number of arguments and stores them as a tuple.
1 2 3 4 | def what_is_args(*args): print(args) what_is_args() |
Output
1 | () |
Thus helps in making a function more flexible in terms of accepting arguments.
1 2 3 4 5 | def add(*args): return sum(args) print(add(5,6,4)) print(add(1,1,1,1,1)) |
Output
1 2 | 15 5 |
What to do? to pass variable and different types of arguments to a function.
In this **kwargs comes handy. Let’s see what is it?
What is **Kwargs in Python?
**kwargs is a Keyword argument which can accept different types of arguments and stores them as a dictionary.
1 2 3 4 | def what_is_kwargs(**kwargs): print(kwargs) what_is_kwargs() |
Output
1 | {} |
Without **kwargs:
1 2 3 4 5 | def student(name, roll): print(name) print(roll) student(name="pencil", roll=77) |
Output
1 2 | pencil 77 |
With **kwargs:
1 2 3 4 5 6 | def student(**kwargs): print(kwargs) print(kwargs['name']) print(kwargs['roll']) student(name="pencil", roll=77) |
Output
1 2 3 | {'name': 'pencil', 'roll': 77} pencil 77 |
It allows a function to accept more than one type of arguments thus makes them more flexible in terms of types of arguments.
1 2 3 4 5 | def website(**kwargs): print(kwargs['name']) print(kwargs['domain']) website(name='Pencil Programmer', domain='https://pencilprogrammer.com') |
Output
1 2 | Pencil Programmer https://pencilprogrammer.com |
Note: we can use any names instead of args and kwargs, what makes them meaningful is * (single asterisk) to make it Non-Keyword Argument and ** (Double asterisks) to make it Keyword Argument.
Hope now you got little idea about *args and **kwargs in python and will be able to use it in your programs. Any doubts then comment below.