*args & **kwargs in python

Balaji Sundararaman
3 min readJun 14, 2021

..demistyfied & how to use them

Photo by Joan Gamell on Unsplash

How many times have we come across *args and **kwargs mentioned in the python functions help documents. Have you wondered what these mean and how is it used?

Well, here are the answers !

*args

*args` refers to arguments or the parameters we pass to a function so that it can work on these arguments and what it is supposed to do. For the sake of an example, lets create a user-defined function that takes in 2 arguments and returns the sum.

Image by the author

Here we have not explicitly passed the names of the arguments x and y. python assumes that the first argument refers to x and the second to y and this method is also referred to as passing positional arguments. But what if we want to create a function to add 3 numbers? Or 4 numbers? The above function does not work for more than 2 numeric arguments:

Image by the author

We would not like to keep creating new functions just to add this capability right? We would want a function that can be flexible to take in any number of arguments and perform the same task as the one above.

Here is where the *args technique comes in handy. Let's create a new function that performs the same task, but can take an unspecified number of arguments.

Using the *args technique we can unpack the arguments passed into the function as a list inside the function and do what we need to do with it inside the function.

Image by author
Image by the author

**kwargs

kwargs refers to key word arguments. This technique is when we explicitly pass the argument names, like so:

Image by author

The above is a very simple function for created for the sake of demonstration. But imagine a function that takes in a ton of arguments. Then the function call can become very long and result in a cluttered line of code. **kwargs technique comes in very handy in such situations.

We can create a dictionary of the argument names and the value we want to pass as key-value pairs in the dictionary and just pass the dictionary to the function prefixed by **. The dictionary elements are unpacked inside the function and the respective argument values processed.

--

--

Balaji Sundararaman

Passionate about Data Analytics, Visualization and Machine Learning with extensive experience across functions in India’s emerging Fintech vertical