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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Dictionaries in Python (Tutorial)
- Python args and kwargs: Demystified (Course)
- Python args and kwargs: Demystified (Quiz)
- Using Dictionaries in Python (Course)
- Python Dictionaries (Quiz)
- Dictionaries in Python (Quiz)
By Leodanis Pozo Ramos • Updated April 17, 2025