The world’s leading publication for data science, AI, and ML professionals.

*args and **kwargs in Python

Understanding what *args and **kwargs are and how to use them

Photo by Fotis Fotopoulos on Unsplash
Photo by Fotis Fotopoulos on Unsplash

Introduction

Let’s say that we want to write a function that makes a list of what we need to purchase from the grocery store. In other words, as we think of items to add (which could vary), we call the function, pass in the items we want to add to the list, and those items get added to the grocery list. Well, we could try something like this:

grocery_list = []
def add_items(item):
    grocery_list.append(item)
add_items('apples')
print(grocery_list)
#['apples']

Sure this works, but we usually remember a few items at a time to add to the list. And the number of items we remember at different times may vary. In other words, we may want to add two items at one time, three items the next, and one item after that. We could just add those items in one at a time with each call of the function. Or we could just enclose those items in a list and pass that list to the function. But why have the inconvenience of wrapping our items in some type of sequence? Is there a way to pass in a different number of items with each call of the function without wrapping them in a sequence? That’s where args and kwargs come in!

But before discussing args and kwargs, we need to briefly review the unpacking operators.


The * Operator

The unpacking operator, *, can be used to pack multiple values into a single variable. For example:

*items, = 'bananas', 'apples', 'toast'
# items
['bananas', 'apples', 'toast']

The reason for using a trailing comma after *items is because the left side of the assignment must be a tuple or list. Therefore, the items variable now contains all the items on the right side in the form of a list.

So let’s imagine that that with each call of the function, this packing of multiple values happens. In other words, no matter how many arguments we pass in to our function, they will be packed into one variable (parameter).

This is what we do when we define functions that can receive a varying number of arguments! That is the concept of *args and **kwargs!


The Ultimate Guide to Sorting in Python


*args

Let’s say we have a function, grocery_list, that takes in a variable number of items as arguments and adds them to our grocery list. However, the number of items that we pass in to this function can vary. Well, we can’t just choose a number of parameters that this function would have since the number of positional arguments can change with each calling of the function. We can instead use the * operator to pack the arguments passed in into a tuple as follows:

grocery_list = []
def add_items(*args):
    print(args)
    grocery_list.extend(args)
add_items('apples', 'bananas','sugar')
#('apples', 'bananas', 'sugar') #since we use a print statement in the function
print(grocery_list)
#['apples', 'bananas', 'sugar']

We use the print() function to show that the arguments passed to the function, args, are packed into one tuple. And since the extend() list method can take any iterable object to extend the list, we can pass in that tuple.

No matter what number of positional arguments we pass in when we call the add_items function, the *args* argument will pack the positional arguments into a tuple, similar to the items** assignment above.

# pass in two items this time
add_items('bread', 'pasta')
('bread', 'pasta')
print(grocery_list)
['apples', 'bananas', 'sugar', 'bread', 'pasta']

**kwargs

To pass in a varying number of keyword or named arguments, we use the operator when defining a function. The unpacking operator will pack the varying number of named arguments we pass in into a dictionary.

def names_dict(**kwargs):
    return kwargs
names_dict(Jane = 'Doe')
# {'Jane': 'Doe'}
names_dict(Jane = 'Doe', John = 'Smith')
# {'Jane': 'Doe', 'John': 'Smith'}

Note: When using the * operator to create a parameter that receives a varying number of positional arguments when defining a function, it is common to use the parameter name args (and kwargs to receive a varying number of keyword or named arguments). However, any names can be chosen for these parameters.


If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.

Join Medium with my referral link – Luay Matalka


Conclusion

In this tutorial, we briefly reviewed the unpacking operators, * and , and how they can be used to pack multiple items into one variable. We then used this concept to discuss the functionality of *args and *kwargs (arguments and keyword arguments, respectively). Lastly, we learned how args can be used to pass in a variable number of positional arguments into a tuple, and kwargs can be used to pass in a variable number of keyword arguments into a dictionary.


Related Articles