0
0
PythonComparisonBeginner · 3 min read

Args vs Kwargs in Python: Key Differences and Usage

In Python, *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 argumentsPositional argumentsKeyword (named) arguments
Data structure receivedTupleDictionary
Syntax in function definition*args**kwargs
Order matters?Yes, order of arguments is preservedNo, order of keys is not guaranteed (before Python 3.6)
Use caseWhen number of positional args is unknownWhen number of named args is unknown
Access inside functionBy index like a tupleBy 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.

python
def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

result = sum_all(1, 2, 3, 4)
print(result)
Output
10
↔️

**kwargs Equivalent

This example shows how to use **kwargs to print named arguments and their values.

python
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=30, city="NY")
Output
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.
Use *args for unnamed arguments and **kwargs for named arguments.
Order matters with *args, while **kwargs handles named pairs.
You can combine both to write flexible functions.