Python *args and **kwargs: Passing Variable Arguments
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. Use them when you do not know in advance how many values a function will receive, or when you want a function to accept flexible input without writing many separate parameters. The rest of this article shows how they work, how to read them, and how to avoid the mistakes that cause confusing argument errors.
Difficulty: Beginner
Helpful to know first: basic Python functions, positional and keyword arguments, and tuples and dictionaries.
How *args and **kwargs Collect Extra Arguments
In Python, a function normally has a fixed list of parameters. That works well when you know exactly how many values the function needs. Sometimes, though, you want the function to accept a flexible number of values.
*args means “gather extra positional arguments here.” Python puts those extra values into a tuple. **kwargs means “gather extra keyword arguments here.” Python puts those extra name-value pairs into a dictionary.
Here is the smallest useful example of each:
def show_args(*args):
print(args)
show_args(1, 2, 3) # Output: (1, 2, 3)
def show_kwargs(**kwargs):
print(kwargs)
show_kwargs(name="Ada", age=36) # Output: {'name': 'Ada', 'age': 36}In the first function, Python packs the extra positional values into a tuple named args. In the second, it packs the keyword pairs into a dictionary named kwargs. The names args and kwargs are only conventions, but they are so common that most Python code uses them.
Using *args for Flexible Positional Values
Use *args when the order of values matters, but the number of values can change. Common examples include totals, averages, logging helpers, and wrapper functions.
Summing an unknown number of numbers
Suppose you want a function that adds any number of numbers together. You do not want separate parameters for two numbers, three numbers, or ten numbers.
def total(*numbers):
sum_so_far = 0
for number in numbers:
sum_so_far += number
return sum_so_far
print(total(4, 7, 10)) # Output: 21The function body treats numbers like a tuple. You can loop over it, index it, or pass it to other functions that expect an iterable.
Mixing normal parameters with *args
You can place regular parameters before *args. Those parameters must be filled first.
def describe_pet(species, *traits):
print(species)
print(traits)
describe_pet("cat", "small", "quiet")
# Output:
# cat
# ('small', 'quiet')The first argument, "cat", goes to species. The remaining positional arguments go into traits.
Why *args is useful in wrapper functions
Wrapper functions often do some extra work, then pass the same arguments to another function. *args makes that easy.
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Ava", "Ben")
# Output:
# Hello, Ava!
# Hello, Ben!This pattern appears in decorators, logging helpers, and adapter functions that need to stay generic.
Using **kwargs for Flexible Named Options
Use **kwargs when the names of the options matter more than their order. It is common for configuration, formatting helpers, and functions that pass options to another API.
Reading keyword options as a dictionary
Inside the function, kwargs is a dictionary. You can inspect keys, read values, and provide defaults.
def make_profile(**kwargs):
print(kwargs.get("name", "Unknown"))
print(kwargs.get("city", "Not provided"))
make_profile(name="Mina")
# Output:
# Mina
# Not providedUsing dict.get() is safer than direct indexing when a key may be missing.
Collecting options for later use
A common pattern is to accept unknown options, then forward them somewhere else.
def format_person(**kwargs):
return f"{kwargs['first']} {kwargs['last']}"
print(format_person(first="Grace", last="Hopper"))
# Output: Grace HopperIf a caller does not pass the expected keys, this version raises a KeyError. That is useful when those keys are required.
Using *args and **kwargs Together
You can accept both flexible positional values and flexible named values in one function. Put *args before **kwargs.
def report(*args, **kwargs):
print(args)
print(kwargs)
report(1, 2, mode="fast", debug=True)
# Output:
# (1, 2)
# {'mode': 'fast', 'debug': True}This is the common shape for very flexible helper functions. The function can accept any number of positional arguments, any number of keyword arguments, or both.
Where the fixed parameters go
You can still use normal parameters before *args and after keyword-only markers. A common pattern is a required value first, then extra positional arguments, then extra keyword arguments.
def build_message(title, *parts, **options):
text = " ".join(parts)
print(title)
print(text)
print(options)
build_message("News", "Python", "is", "fun", style="bold")
# Output:
# News
# Python is fun
# {'style': 'bold'}This structure makes the required input obvious while still allowing flexible extra data.
How Python Binds Arguments to Parameters
Python matches arguments to parameters in a strict order. Understanding that order prevents most mistakes.
First, Python assigns positional arguments from left to right. Then it assigns keyword arguments by name. After that, any leftover positional values go into *args, and any leftover keyword pairs go into **kwargs.
The names args and kwargs are only conventions. You could name them values and options, but that is less readable in Python code.
A function can also define keyword-only parameters after a bare *. That is related to **kwargs, but not the same thing. Keyword-only parameters must be passed by name; **kwargs collects unknown names.
def show_settings(*, theme="light", font_size=12):
print(theme)
print(font_size)
show_settings(theme="dark")
# Output:
# dark
# 12Here, the bare * means there are no positional parameters after it. The arguments must be named.
What Happens When You Use *args and **kwargs at the Call Site
The same symbols are also used when calling a function. At the call site, *sequence unpacks a sequence into positional arguments, and **mapping unpacks a dictionary into keyword arguments.
def announce(first, second, *, loud=False):
print(first, second, loud)
items = ["hello", "world"]
options = {"loud": True}
announce(*items, **options)
# Output: hello world TrueThis is not the same as defining *args and **kwargs, but the symbols look similar. At the call site, they unpack values. In a function definition, they collect values.
How *args and **kwargs Behave in Detail
There are a few details that beginners often miss. These details explain many surprising results and error messages.
*args is always a tuple
Inside the function, extra positional arguments are stored in a tuple. That means the value is ordered, immutable, and easy to iterate over.
def inspect_args(*args):
print(type(args))
inspect_args(5, 8)
# Output: <class 'tuple'>**kwargs is always a dictionary
The keyword arguments are stored in a dictionary. Since Python 3.7, dictionaries preserve insertion order as a language guarantee, so the order you pass keyword arguments is the order you usually see when printing the dictionary.
def inspect_kwargs(**kwargs):
print(type(kwargs))
inspect_kwargs(city="Oslo", country="Norway")
# Output: <class 'dict'>Duplicate values cause a TypeError
If a value is given both positionally and by name, Python raises an error before the function body runs.
def introduce(name):
print(name)
# introduce("Ada", name="Grace")
# TypeError: introduce() got multiple values for argument 'name'This happens because Python cannot decide which value should win. The fix is to pass the argument only once.
Predict the Output
Extra positional values and extra keyword values
def sample(*args, **kwargs):
print(args)
print(kwargs)
sample(1, 2, x=3)What does this print?
Show answer
It prints a tuple for the positional values and a dictionary for the keyword values:
# Output:
# (1, 2)
# {'x': 3}Python puts 1 and 2 into args, then puts x=3 into kwargs.
Mixing unpacking and normal arguments
def combine(a, b, *rest):
print(a, b, rest)
values = [10, 20, 30]
combine(*values)What does this print?
Show answer
It prints the first two values into a and b, then stores the remaining value in rest:
# Output: 10 20 (30,)The star at the call site unpacks the list into three positional arguments, and the function collects the leftover positional value in a tuple.
Common Mistakes
Trying to use *args as a list you can change
args looks like a list to beginners, but it is a tuple. Tuples cannot be changed in place.
Problem: The code tries to append to args, but tuples do not have an append() method.
def add_item(*args):
args.append(4)
print(args)
add_item(1, 2)Fix: Create a new list if you need to add or remove items.
def add_item(*args):
items = list(args)
items.append(4)
print(items)
add_item(1, 2)The corrected version works because it copies the tuple into a mutable list first.
Forgetting that **kwargs must come after *args
In a function definition, **kwargs must be the last parameter. Python reads the parameter list from left to right and does not allow anything after it.
Problem: This definition puts a normal parameter after **kwargs, which is invalid syntax.
def broken(**kwargs, name):
print(kwargs, name)Fix: Put required parameters first, then *args, then **kwargs.
def broken(name, **kwargs):
print(kwargs, name)
broken("Ada", role="engineer")The corrected version works because the function signature now follows Python's parameter order rules.
Passing the same argument twice
A common bug is to provide a value both positionally and as a keyword argument. Python rejects that before the function runs.
Problem: The value for name is supplied twice, so Python cannot bind the argument unambiguously.
def welcome(name):
print(f"Hello, {name}")
welcome("Ava", name="Ben")Fix: Pass the value one way only.
def welcome(name):
print(f"Hello, {name}")
welcome("Ava")
welcome(name="Ben")The fixed version works because each call gives name exactly one value.
Find the Bug
Someone wrote a flexible logging helper, but it does not behave the way they expected. Find the bug in the function definition.
def log_message(**kwargs, prefix="INFO"):
print(prefix, kwargs)
log_message(user="maya")What is wrong, and how should it be fixed?
Show answer
The bug is the parameter order. **kwargs must be the last parameter in the function definition. Nothing can come after it, not even a default parameter.
Fixed code:
def log_message(*args, prefix="INFO", **kwargs):
print(prefix, kwargs)
log_message(user="maya")
# Output: INFO {'user': 'maya'}The fixed version works because Python can now parse the parameter list, and prefix remains a keyword-only option.
When to Use *args and **kwargs, and When to Use Something Else
Use flexible argument collection only when the function really needs it. A fixed parameter list is usually clearer if the inputs are known and stable.
| Situation | Better choice | Why |
|---|---|---|
| You know every parameter in advance | Regular named parameters | Clearer call sites and better error messages |
| You need any number of positional values | *args | Collects extra ordered values cleanly |
| You need optional named settings | **kwargs or keyword-only parameters | Readers can see option names directly |
| You are forwarding arguments to another function | *args and **kwargs | Preserves the original call shape |
For public APIs, keyword-only parameters are often better than accepting arbitrary keywords. They tell callers exactly which names are allowed, and Python can catch mistakes sooner. Use **kwargs when the set of keys is truly open-ended or when you are building a wrapper around another function.
Interview Questions
What is the difference between *args and **kwargs?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. They solve different problems, and many functions use both together.
Why are the names args and kwargs used so often?
They are conventions, not special keywords. The names help readers recognize the intent of the function quickly. Other names are allowed, but these names are the Python community standard.
Can I have normal parameters after *args?
No, not as positional parameters. After *args, additional parameters must be keyword-only unless the parameter list ends with **kwargs. This is useful when you want to force callers to name certain options.
Try It Yourself
Write a function named menu_item that:
- accepts one required positional parameter for the item name,
- accepts any number of extra positional toppings,
- accepts an optional keyword argument named size with the default value "medium",
- prints the item name, the toppings tuple, and the size.
Expected output:
Pizza
('olives', 'mushrooms')
largeHint: Put the required parameter first, then *args, then the keyword-only size parameter.
Show solution
def menu_item(name, *toppings, size="medium"):
print(name)
print(toppings)
print(size)
menu_item("Pizza", "olives", "mushrooms", size="large")Summary
- *args collects extra positional arguments into a tuple.
- **kwargs collects extra keyword arguments into a dictionary.
- The names args and kwargs are conventions, not keywords.
- In a function definition, *args must come before **kwargs.
- At the call site, * unpacks a sequence and ** unpacks a mapping.
- Use fixed parameters when you know the inputs, and use *args or **kwargs when flexibility is the real goal.
Next, learn how keyword-only parameters work in Python, because they are the closest tool for designing clear function APIs alongside *args and **kwargs.