Passing Multiple Arguments to a Function
Hi, I’m Rich Bibby with realpython.com. Sometimes when you look at a function definition in Python you might see that it takes two strange arguments,
If you’ve ever wondered what these peculiar variables are or why your IDE defines them in
main(), then this tutorial is for you. You’ll learn how to use
kwargs in Python to add more flexibility to your functions. In this tutorial, you’re going to learn what
**kwargs actually are and how they allow you to pass multiple arguments or keyword arguments to a function.
Then you’ll learn how to use the
*args variable in function definitions, and then also how to use the
**kwargs variable in function definitions.
Then, once you’ve learned to write functions that use
kwargs, you’ll then learn about why the ordering of arguments becomes important.
Next, you’ll learn how to use single asterisks (
*) to unpack iterables and also how to use double asterisks (
**) to unpack dictionaries. And finally, we’ll wrap things up in the conclusion.
01:00 This tutorial assumes that you already know how to define Python functions and work with lists and dictionaries. If you don’t or if you need a refresher, then check out some of the other great tutorials here on realpython.com that cover these topics. So, let’s get started.
**kwargs allow you to pass multiple arguments, in the case of
*args, or keyword arguments, in the case of
**kwargs, to a function. Consider this example.
This is a simple function that takes two arguments,
b, and returns their sum. This function works fine, but it’s limited to only two arguments. What if you need to sum a varying number of arguments, where the specific number of arguments passed is only determined at runtime?
01:43 Wouldn’t it be great to create a function that could sum all the integers passed to it, no matter how many there are? Of course it would. So keep watching, and I’ll show you how you can do just that.
Become a Member to join the conversation.