kwargs (keyword arguments)

In Python, **kwargs is a special syntax for defining functions that accept an undetermined number of keyword arguments.

The kwargs argument captures any extra keyword arguments into a dictionary, where the keys are the argument names and the values are the actual arguments. This behavior allows your function to handle any number of keyword arguments gracefully, making your code more dynamic and adaptable.

Using **kwargs can be particularly beneficial in scenarios where you want to take an unknown number of arguments or when you want to accept optional argument.

Example

Here’s a quick example demonstrating how to use **kwargs in a Python function:

Python
>>> def concatenate(**kwargs):
...     return " ".join(kwargs.values())
...

>>> concatenate(a="Welcome", b="to", c="Real", d="Python!")
'Welcome to Real Python!'

In this example, the concatenate() function can take any number of keyword arguments. The function packs all the keyword arguments in a dictionary. Next, you use the str.join() method to concatenate the arguments and generate a final string.

Tutorial

Python args and kwargs: Demystified

In this step-by-step tutorial, you'll learn how to use args and kwargs in Python to add more flexibility to your functions. You'll also take a closer look at the single and double-asterisk unpacking operators, which you can use to unpack any iterable object in Python.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 17, 2025