Flat_Eric Contemplating Data Type Conversions

*args and **kwargs

*args and **kwargs

So far every function we have written has taken a fixed number of parameters. But what if you do not know in advance how many arguments will be passed in? What if you want a function that can handle one argument or one hundred without rewriting it each time?

That is exactly what *args and **kwargs are for.

*args

*args allows a function to accept any number of positional arguments. Instead of defining a fixed number of parameters, the single *args parameter collects all the positional arguments passed in and packages them into a tuple inside the function.

The * is what does the work. The word args is just a convention. You could call it *numbers or *items and it would work exactly the same way. But *args is what every developer expects to see so stick with it.

Without *args a function that adds numbers would need a fixed number of parameters:

This works for exactly two numbers. But what if you need to add three? Or ten? With *args the function handles any number of arguments without any changes:

Because *args is a tuple inside the function we can loop over it, pass it to other functions or use any tuple operation on it. This makes it extremely flexible.

**kwargs

**kwargs works the same way but for keyword arguments. Instead of collecting positional arguments into a tuple, it collects keyword arguments into a dictionary where each keyword becomes a key and each value becomes the corresponding value.

Again the ** is what does the work and kwargs is just a convention. You will see it written as **kwargs everywhere so keep it consistent.

Because **kwargs is a dictionary inside the function we can iterate over it using .items() just like any other dictionary. This makes it perfect for situations where you want to pass in a flexible set of named options or settings.

Using *args and **kwargs Together

You can use both in the same function. When you do, the order matters. Regular parameters come first, then *args, then **kwargs. Python will throw an error if you mix up the order.

In the example below we create a function that takes a label as a regular parameter, a set of numbers via *args and a set of additional details via **kwargs. The function adds all the numbers together and displays the result alongside the keyword details.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: *args Basic

Exercise 2: *args with a Condition

Exercise 3: **kwargs Basic

Exercise 4: *args and **kwargs Together

Exercise 5: Real World *args and **kwargs

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course