Last modified: Nov 19, 2026
Python *args and **kwargs Explained
Python functions are flexible. You can pass a fixed number of values. You can also pass any number of values. The *args and **kwargs syntax makes this possible.
These two features confuse many beginners. The stars look strange. The names seem random. But the idea is simple once you see it in action.
This guide explains both features step by step. You will see clear examples, real output, and common pitfalls. By the end, you will know exactly when and how to use them.
What Are *args in Python?
The *args parameter lets a function accept any number of positional arguments. Python collects the extra values into a tuple.
The name args is a convention. The star is what matters. You could name it *numbers or *values and it would still work.
Here is a simple example:
def add_all(*args):
# args is a tuple of all positional arguments
print(type(args))
print(args)
return sum(args)
result = add_all(1, 2, 3, 4)
print(result)
(1, 2, 3, 4)
10
Notice two things. First, args is a tuple. Second, the function works with any count of numbers.
Call it with one value, five values, or zero values. It never breaks.
print(add_all(5)) # 5
print(add_all()) # 0
print(add_all(10, 20)) # 30
This pattern is common in real code. Think of functions like print or max. They accept many values without a fixed limit.
Mixing *args with Regular Parameters
You can combine normal parameters with *args. The rule is simple. Regular parameters come first. Then the star parameter.
def greet(greeting, *names):
# greeting takes the first value
# names collects the rest as a tuple
for name in names:
print(f"{greeting}, {name}!")
greet("Hello", "Alice", "Bob", "Carol")
Hello, Alice!
Hello, Bob!
Hello, Carol!
Python fills greeting first. Everything else goes into names. This order is mandatory. You cannot put *args before a regular parameter.
What Are **kwargs in Python?
The **kwargs parameter accepts any number of keyword arguments. Python collects them into a dictionary.
Again, the name is a convention. The double star is what matters.
def show_profile(**kwargs):
# kwargs is a dict of keyword arguments
print(type(kwargs))
for key, value in kwargs.items():
print(f"{key}: {value}")
show_profile(name="Alice", age=30, city="Paris")
name: Alice
age: 30
city: Paris
This is useful when a function needs optional named settings. You do not need to define every possible key in advance.
You can loop over the dictionary easily. You can also access single keys with kwargs.get(). This is a safe way to read optional values.
Combining *args and **kwargs
You can use both in the same function. The order matters. It must be regular parameters, then *args, then **kwargs.
def order_summary(customer, *items, **details):
print(f"Customer: {customer}")
print(f"Items: {items}")
print(f"Details: {details}")
order_summary("Alice", "apple", "bread", rush=True, gift=False)
Customer: Alice
Items: ('apple', 'bread')
Details: {'rush': True, 'gift': False}
This structure gives you maximum flexibility. One function can handle simple calls and complex calls.
Unpacking with the Star Operator
The star does more than collect values. It also unpacks them when you call a function.
You can pass a list or tuple as separate positional arguments. You can pass a dictionary as separate keyword arguments.
def multiply(a, b, c):
return a * b * c
numbers = [2, 3, 4]
print(multiply(*numbers)) # unpack list into three arguments
24
The same trick works with dictionaries and **kwargs:
def describe(name, age):
print(f"{name} is {age} years old")
info = {"name": "Bob", "age": 25}
describe(**info) # unpack dict into keyword arguments
Bob is 25 years old
This pattern appears often with functions that work on iterables. If you enjoy tools like these, the guide on the Python map function shows how unpacking pairs well with data processing.
Common Use Cases
Where do you see *args and **kwargs in real projects? Here are the most common cases.
Wrappers and decorators. A decorator often passes unknown arguments to the wrapped function. Using both stars makes it universal.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs) # forward all arguments
return wrapper
@logger
def add(a, b):
return a + b
print(add(2, 3))
Calling add
5
Configuration objects. Functions like matplotlib.plot accept many optional settings. **kwargs makes this clean.
Flexible APIs. Library authors use these features to keep functions future-proof. New options do not break old code.
Best Practices and Pitfalls
These features are powerful, but they need care. Follow these rules to keep your code clean.
Use clear names. args and kwargs are fine for generic wrappers. For real logic, use names like *scores or **options.
Document what you expect. A reader should know which keys **kwargs supports. List them in the docstring.
Validate input. Since *args accepts anything, check types and counts when it matters.
Avoid overuse. If a function takes exactly two values, use two parameters. Stars are for true flexibility.
Remember the order rule. Wrong order causes a SyntaxError before your code even runs.
Also watch out for name clashes. A key inside kwargs can conflict with a regular parameter name. Python raises a TypeError in that case.
Quick Comparison Table
Here is a simple summary to keep things clear:
Feature | Collects | Type | Call syntax
*args | Positional values | tuple | func(*iterable)
**kwargs | Keyword values | dict | func(**mapping)
Keep this table in mind. It answers most questions at a glance.
These patterns also show up when you filter or pair data. For example, the Python filter function with examples often combines with flexible helper functions in real scripts.
Putting It All Together
Let us build one complete example. It uses regular parameters, *args, and **kwargs together.
def build_report(title, *rows, **options):
# title is required
# rows collects table lines
# options holds display settings
print(f"=== {title} ===")
for row in rows:
print(row)
if options.get("show_total"):
print(f"Total rows: {len(rows)}")
build_report("Sales", "Q1: 100", "Q2: 150", show_total=True)
=== Sales ===
Q1: 100
Q2: 150
Total rows: 2
This function is short but flexible. It handles any number of rows and any display flag.
You can extend it later without breaking existing calls. That is the real value of these features.
If you work with sorted data, the article on how to find max and min in a list pairs nicely with flexible functions like this one.
Conclusion
Python *args and **kwargs are simple once you know the rules. One star collects positional values into a tuple. Two stars collect keyword values into a dictionary.
They make functions flexible and future-proof. They power decorators, wrappers, and library APIs.
Start small. Add *args to one function that needs many values. Add **kwargs to one function with optional settings. Practice with the examples above.
Soon these stars will feel natural. Your code will be shorter, cleaner, and easier to extend.