Python functions are flexible about how they receive arguments. Parameters can have default values, callers can pass arguments by name, and a function can accept any number of extra values with *args and **kwargs. This lesson explains each kind of parameter, how the star operators also unpack lists and dictionaries in calls, and the mutable-default bug that surprises almost every Python learner.
In this lesson you will learn
- Default values and keyword arguments
- Collecting extra positional arguments with
*args - Collecting extra keyword arguments with
**kwargs - Unpacking with
*and**in a call - Keyword-only and positional-only parameters
- Why a list should never be a default value
Defaults, Keywords, *args and **kwargs
def greet(name, greeting="Hello"): # default value
return f"{greeting}, {name}!"
print(greet("Nadia"))
print(greet("Rafi", "Good morning"))
print(greet(greeting="Hi", name="Mitu")) # keyword arguments, any order
def total(*numbers): # any number of positional arguments
print(type(numbers).__name__, numbers)
return sum(numbers)
print(total(5, 10, 15))
print(total())
def profile(name, **details): # any number of keyword arguments
print(name, details)
profile("Tania", dept="CSE", cgpa=3.95)
Output
Hello, Nadia!
Good morning, Rafi!
Hi, Mitu!
tuple (5, 10, 15)
30
tuple ()
0
Tania {'dept': 'CSE', 'cgpa': 3.95}
greeting="Hello"gives the parameter a default, so callers may leave it out. Parameters with defaults must come after those without.- Keyword arguments such as
name="Mitu"are matched by name, so their order does not matter and calls become self-explanatory. *numberscollects any extra positional arguments into a tuple. With no arguments it is an empty tuple.**detailscollects extra keyword arguments into a dictionary.- The names
argsandkwargsare only conventions; the*and**do the work.
Combining, Unpacking and Special Parameters
def report(title, *values, sep=", ", **options):
text = sep.join(str(v) for v in values)
if options.get("upper"):
text = text.upper()
print(f"{title}: {text}")
report("Cities", "Dhaka", "Sylhet")
report("Marks", 78, 91, 64, sep=" | ")
report("Depts", "cse", "eee", upper=True)
# Unpacking a list and a dict into a call
marks = [70, 85, 90]
settings = {"sep": " - ", "upper": False}
report("Unpacked", *marks, **settings)
# Keyword-only (after *) and positional-only (before /) parameters
def area(width, height, /, *, unit="m"):
return f"{width * height} {unit}^2"
print(area(3, 4))
print(area(3, 4, unit="cm"))
try:
area(width=3, height=4)
except TypeError as e:
print("TypeError:", e)
# The mutable default trap
def add_item(item, bag=[]):
bag.append(item)
return bag
print(add_item("pen"), add_item("book"))
def add_item_fixed(item, bag=None):
if bag is None:
bag = []
bag.append(item)
return bag
print(add_item_fixed("pen"), add_item_fixed("book"))
Output
Cities: Dhaka, Sylhet
Marks: 78 | 91 | 64
Depts: CSE, EEE
Unpacked: 70 - 85 - 90
12 m^2
12 cm^2
TypeError: area() got some positional-only arguments passed as keyword arguments: 'width, height'
['pen', 'book'] ['pen', 'book']
['pen'] ['book']
- The full order of parameters is: normal ones,
*args, keyword-only ones, then**kwargs. Inreport,sepcomes after*values, so it can only be passed by name. - In a call, the stars work in reverse:
*marksspreads a list into separate positional arguments and**settingsspreads a dictionary into keyword arguments. - A bare
*in the parameter list makes everything after it keyword-only; a/makes everything before it positional-only.area(width=3, height=4)is therefore rejected. - The mutable default trap: a default value is created once, when the function is defined, not on each call. Both calls to
add_itemshare the same list. UseNoneas the default and create a new list inside the function.
Parameter Kinds at a Glance
| Syntax | Name | Receives |
|---|---|---|
def f(a) | Positional or keyword | One value |
def f(a=1) | With default | One value, optional |
def f(*args) | Var-positional | Tuple of extra positional values |
def f(*, a) | Keyword-only | Must be passed as a=... |
def f(a, /) | Positional-only | Must be passed by position |
def f(**kwargs) | Var-keyword | Dict of extra keyword values |
*args and **kwargs are common in decorators, which must pass along whatever arguments the wrapped function receives.
Common Mistakes
- Using a list or dict as a default value; use
None. - Putting a defaulted parameter before a required one, which is a syntax error.
- Passing the same argument twice, by position and by name, which raises
TypeError. - Forgetting the star when unpacking:
total(marks)passes one list, not three numbers.
Practice Exercises
Exercise 1. Write average(*nums) that returns the average of any number of values, or 0 if none are given.
Show answer
def average(*nums):
return sum(nums) / len(nums) if nums else 0
print(average(70, 80, 90), average()) # 80.0 0
Exercise 2. Write tag(name, **attrs) that builds an HTML tag string, so tag("a", href="/home") returns <a href="/home">.
Show answer
def tag(name, **attrs):
parts = "".join(f' {k}="{v}"' for k, v in attrs.items())
return f"<{name}{parts}>"
print(tag("a", href="/home"))
Frequently Asked Questions
Are *args and **kwargs required names?
No. Any names work, such as *numbers or **options. The single and double stars are what matter; args and kwargs are just the usual choice.
Can I merge two dictionaries with **?
Yes: {**a, **b} creates a new dict, with values from b winning on duplicate keys. Since Python 3.9 you can also write a | b.
Summary
- Defaults make parameters optional; keyword arguments make calls clear.
*argsgathers a tuple,**kwargsgathers a dict.- In calls,
*and**unpack lists and dicts. *and/mark keyword-only and positional-only parameters.- Never use a mutable object as a default value.
Next: Python Recursion.
