Default Arguments, *args, and **kwargs
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Default arguments make parameters optional. When you do not know in advance how many arguments a caller will pass, Python's *args and **kwargs provide complete flexibility.
Default parameter values
Default argument is a value written in the def line, as in priority="normal". Python uses it when the caller leaves that argument out.
Assign a default value in the function header: param=default. If the caller omits the argument, Python uses the default.
def send_email(to, subject, priority="normal"): print(f"To: {to} | Sub: {subject} | Priority: {priority}")
send_email("team@mentornxt.com", "Sprint Review")send_email("ceo@mentornxt.com", "Urgent Alert", priority="high")Example 1 · Optional shipping rate
def ship_cost(weight, rate=40): return weight * rate
print(ship_cost(3))print(ship_cost(3, 55))120 165
What this code does
- The first call leaves
rateout, so Python uses 40: 3 * 40 = 120. - The second call gives 55, which replaces the default: 3 * 55 = 165.
The first call uses the default 'normal', while the second call overrides it with 'high'.
A default is created only once
Default evaluated once means Python works out a default value a single time, when def runs, and reuses it on every call. A changeable default, such as a list, is therefore shared between calls.
Python works out a default value once, when def runs, not on every call.
def announce(): print("Creating default") return "normal"
def send(to, priority=announce()): print(f"To {to}, priority {priority}")
print("Function defined")send("Asha")send("Ravi")A default such as announce() below is therefore reused by every call.
Example 2 · None as a safe default
def greet(name, title=None): if title is None: title = "Customer" return f"Hello, {title} {name}"
print(greet("Asha"))print(greet("Rao", "Dr"))Hello, Customer Asha Hello, Dr Rao
What this code does
Noneis a default that is safe to share, because it never changes.- The function replaces it with a fresh value inside, only when the caller gave none.
Creating default prints once, before the first call, and both calls reuse that value. This matters most for a list used as a default, because every call would share one list (Lists (opens in a new tab) comes later). When a default must be fresh, use None and create the value inside the function.
Arbitrary arguments: *args and **kwargs
args and *kwargs are parameters that collect extra positional arguments into a tuple and extra keyword arguments into a dictionary.
*args collects extra positional arguments into a tuple (a fixed group of values, see Tuples (opens in a new tab)). **kwargs collects extra keyword arguments into a dictionary (names with values, see Dictionaries (opens in a new tab)).
def total_sum(*numbers): total = 0 for n in numbers: total += n return total
print(total_sum(1, 2, 3, 4, 5))Example 3 · Server options
def configure_server(host, port=8000, **options): print(f"Host: {host}:{port}") print(options)
configure_server("localhost", debug=True, timeout=30)Host: localhost:8000
{'debug': True, 'timeout': 30}What this code does
hostis positional ('localhost').portuses the default 8000.**optionscollectsdebug=Trueandtimeout=30into one dictionary, whichprintshows with braces.
Example 4 · Any number of marks
def average(*marks): total = 0 count = 0 for mark in marks: total += mark count += 1 return total / count
print(average(80, 90))print(average(70, 80, 90))85.0 80.0
What this code does
*markscollects all the values, and the loop adds them while counting them.- The same function handles two marks and three marks.
You can pass as many numbers as you like. *numbers bundles them together, and a for loop visits each one.
Next step
Check your understanding
9 quick questions