Args vs Kwargs in Python: Key Differences and Usage
*args lets you pass a variable number of positional arguments to a function as a tuple, while **kwargs allows passing a variable number of keyword arguments as a dictionary. Use *args when you want to handle unnamed arguments and **kwargs for named arguments.Quick Comparison
Here is a quick side-by-side comparison of *args and **kwargs in Python.
| Feature | *args | **kwargs |
|---|---|---|
| Type of arguments | Positional arguments | Keyword (named) arguments |
| Data structure received | Tuple | Dictionary |
| Syntax in function definition | *args | **kwargs |
| Order matters? | Yes, order of arguments is preserved | No, order of keys is not guaranteed (before Python 3.6) |
| Use case | When number of positional args is unknown | When number of named args is unknown |
| Access inside function | By index like a tuple | By key like a dictionary |
Key Differences
*args collects extra positional arguments passed to a function into a tuple. This means you can pass any number of unnamed arguments, and inside the function, you access them by their position.
On the other hand, **kwargs collects extra keyword arguments into a dictionary. These arguments are named, so you access them by their keys inside the function.
Because *args is a tuple, it preserves the order of arguments, which is important when the order matters. **kwargs is a dictionary, so the order of keys was not guaranteed before Python 3.6, but now it preserves insertion order. Use *args when you want to handle a list of values, and **kwargs when you want to handle named options or settings.
Code Comparison
This example shows how to use *args to sum any number of numbers passed as positional arguments.
def sum_all(*args): total = 0 for num in args: total += num return total result = sum_all(1, 2, 3, 4) print(result)
**kwargs Equivalent
This example shows how to use **kwargs to print named arguments and their values.
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=30, city="NY")
When to Use Which
Choose *args when your function needs to accept a variable number of positional arguments, like a list of items or numbers where order matters.
Choose **kwargs when your function should accept named arguments that act like options or settings, where each argument has a name and value.
Often, you can use both together to make flexible functions that accept any combination of positional and keyword arguments.
Key Takeaways
*args collects extra positional arguments as a tuple.**kwargs collects extra keyword arguments as a dictionary.*args for unnamed arguments and **kwargs for named arguments.*args, while **kwargs handles named pairs.