Python course · Module 5: Functions · Lesson 23 of 63
Quick answer: A default value makes an argument optional: def order_line(name, price, quantity=1). A keyword argument passes a value by name, so order does not matter: order_line(price=40, name="Ruler"). *args collects any number of extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. Never use a list or dictionary as a default value; use None and create a new one inside the function.
In this lesson you will learn:
- how default values and keyword arguments work, and the rules for mixing them
- how
*argsand**kwargsaccept any number of arguments - how
*and**unpack a list or dictionary in a call - what keyword-only and positional-only parameters are
- why
cart=[]as a default is a trap, and theNonefix
Before you start: finish Lesson 22, Python Functions: def, return, Parameters and Docstrings. All examples were tested on Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.
Table of Contents
Default values
Give a parameter a value with = in the def line, and the caller can leave that argument out:
def order_line(name, price, quantity=1):
return f"{quantity} x {name} = {price * quantity} rupees"
print(order_line("Pen", 60))
print(order_line("Pen", 60, 10))
1 x Pen = 60 rupees
10 x Pen = 600 rupees
The first call has no quantity, so quantity gets its default, 1. The second call passes 10, which replaces the default. name and price have no default, so they are still required.
Parameters with defaults must come after the ones without (keyword-only parameters, shown below, are the exception). Otherwise Python cannot tell which value goes where:
def order_line(name, quantity=1, price):
return f"{quantity} x {name} = {price * quantity} rupees"
File "/home/learner/python-course/err1_default_order.py", line 1
def order_line(name, quantity=1, price):
^^^^^
SyntaxError: parameter without a default follows parameter with a default
Keyword arguments
So far every argument was positional: the first value went to the first parameter, and so on. You can also name the parameter in the call. This is a keyword argument:
def order_line(name, price, quantity=1):
return f"{quantity} x {name} = {price * quantity} rupees"
print(order_line("Notebook", 450, quantity=3))
print(order_line(price=40, name="Ruler", quantity=2))
print(order_line("Ruler", quantity=2, price=40))
3 x Notebook = 1350 rupees
2 x Ruler = 80 rupees
2 x Ruler = 80 rupees
Keyword arguments make a call easier to read: quantity=3 says what 3 means. Their order does not matter, as the second call shows. You already used them in Lesson 10: in print("2026", "11", "04", sep="-"), sep is a keyword argument.
The Python tutorial gives three rules. Each one has its own error:
- “keyword arguments must follow positional arguments”.
order_line(name="Pen", 60)givesSyntaxError: positional argument follows keyword argument. - Every keyword must match a parameter name.
order_line("Pen", 60, qty=10)givesTypeError: order_line() got an unexpected keyword argument 'qty'. - “No argument may receive a value more than once.”
order_line("Pen", 60, price=70)givesTypeError: order_line() got multiple values for argument 'price', because 60 already went topriceby position.
*args: any number of positional arguments
Sometimes you do not know how many values the caller will pass. Put * before a parameter name, and it collects all the extra positional arguments into a tuple:
def total(*prices):
print(prices)
return sum(prices)
print(total(450, 60))
print(total(450, 60, 40, 3200))
print(total())
(450, 60)
510
(450, 60, 40, 3200)
3750
()
0
prices is a normal tuple, so sum() can add it. With no arguments it is an empty tuple, and the sum is 0. The name args is only a habit; the * is what matters. Here *prices says more than *args would. This is the same idea as star unpacking in Lesson 16, where *rest collected the leftover items.
Unpack a list with * in a call
If the values are already in a list, put * before it in the call. Python unpacks the list into separate arguments:
def total(*prices):
return sum(prices)
cart = [450, 60, 40]
print(total(*cart))
print(*cart)
print(*cart, sep=" + ")
550
450 60 40
450 + 60 + 40
total(*cart) is the same as total(450, 60, 40). print() works this way too; its full form, which you saw in Lesson 10, is print(*objects, sep=' ', end='\n', ...). Without the star, the whole list becomes one argument, and sum() fails:
def total(*prices):
return sum(prices)
cart = [450, 60, 40]
print(total(cart))
Traceback (most recent call last):
File "/home/learner/python-course/err5_list_to_args.py", line 5, in <module>
print(total(cart))
~~~~~^^^^^^
File "/home/learner/python-course/err5_list_to_args.py", line 2, in total
return sum(prices)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
prices was ([450, 60, 40],), a tuple holding one list, and sum() cannot add a list to the number 0.
**kwargs: any number of keyword arguments
Two stars before a parameter name collect the extra keyword arguments into a dictionary:
def describe(name, **details):
print(name, details)
for key, value in details.items():
print(f" {key}: {value}")
describe("Notebook", price=450, pages=200, colour="blue")
describe("Pen")
Notebook {'price': 450, 'pages': 200, 'colour': 'blue'}
price: 450
pages: 200
colour: blue
Pen {}
Each keyword becomes a key, as a string, and its value becomes the value. You loop over it with .items(), as in Lesson 17. With no extra keywords, details is an empty dictionary. Again, kwargs is only the usual name.
Two stars in a call do the opposite: they unpack a dictionary into keyword arguments:
def order_line(name, price, quantity=1):
return f"{quantity} x {name} = {price * quantity} rupees"
item = {"name": "Backpack", "price": 3200}
print(order_line(**item))
item["quantity"] = 2
print(order_line(**item))
1 x Backpack = 3200 rupees
2 x Backpack = 6400 rupees
order_line(**item) is the same as order_line(name="Backpack", price=3200). The keys must match the parameter names.
All kinds together
One function can use every kind. The order in the def line is: normal parameters, then *args, then parameters that must be named, then **kwargs:
def make_order(customer, *items, express=False, **notes):
print("customer:", customer)
print("items:", items)
print("express:", express)
print("notes:", notes)
make_order("Sara", "Pen", "Ruler", express=True, gift_wrap="yes")
customer: Sara
items: ('Pen', 'Ruler')
express: True
notes: {'gift_wrap': 'yes'}
"Sara" fills customer, the other positional values go into items, express=True matches its own parameter, and the unknown keyword gift_wrap lands in notes. Note that express comes after *items, so it can only be passed by name. The tutorial says such parameters “are ‘keyword-only’ arguments”. The Python FAQ adds that this gives “the positional arguments as a tuple and the keyword arguments as a dictionary”.
Keyword-only and positional-only parameters
You can also make a parameter keyword-only with a star on its own, *, in the def line. It means “everything after this must be named”:
def ship(item, quantity, *, express=False):
fee = 300 if express else 0
return f"{quantity} x {item}, delivery fee {fee}"
print(ship("Pen", 10, express=True))
print(ship("Pen", 10))
10 x Pen, delivery fee 300
10 x Pen, delivery fee 0
ship("Pen", 10, True) would be unclear: what does True mean? Python refuses it with TypeError: ship() takes 2 positional arguments but 3 were given. The caller must write express=True, which is easy to read. (300 if express else 0 is the conditional expression from Lesson 11.)
A / does the opposite: parameters before it are positional-only, so they cannot be passed by name:
def discount(price, percent, /):
return price - price * percent // 100
print(discount(3200, 10))
2880
Calling discount(price=3200, percent=10) gives TypeError: discount() got some positional-only arguments passed as keyword arguments: 'price, percent'. You will mostly meet / in the documentation of built-in functions. For example, the docs show len(object, /) (help(len) says len(obj, /)), so len(obj="Pen") fails with TypeError: len() takes no keyword arguments. The tutorial advises keyword-only parameters “when names have meaning” and the call is clearer with them.
The mutable default argument trap
Here is the most surprising behaviour in this lesson. This function adds an item to a cart, and makes a new empty cart when none is given. Or so it seems:
def add_item(item, cart=[]):
cart.append(item)
return cart
sara = add_item("Pen")
print(sara)
omar = add_item("Backpack")
print(omar)
print(sara)
print(sara is omar)
print(add_item.__defaults__)
['Pen']
['Pen', 'Backpack']
['Pen', 'Backpack']
True
(['Pen', 'Backpack'],)
Omar’s new cart already contains Sara’s pen, and Sara’s cart now has Omar’s backpack. sara is omar is True (is from Lesson 9): both names point to one list. The tutorial explains why: “The default value is evaluated only once.” The [] is made one time, when the def line runs, and stored with the function; the last line shows it in add_item.__defaults__. Every call without a cart argument uses that same list, and append() changes it. This is the aliasing problem from Lesson 15, hidden inside a function.
![Python function arguments, Lesson 23: with cart=[] as the default, two calls to add_item share one list; with cart=None, each call makes its own new list.](https://eteasmasher.com/wp-content/uploads/2026/11/python-lesson-023-mutable-default-shared-list.webp)
The fix, which the Python FAQ calls good practice, is to use None as the default and create a new list inside the function:
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
sara = add_item("Pen")
omar = add_item("Backpack")
print(sara)
print(omar)
print(add_item("Ruler", ["Notebook"]))
['Pen']
['Backpack']
['Notebook', 'Ruler']
Now cart = [] runs inside the function, on every call that has no cart, so each customer gets a new list. Passing a list still works, as the last line shows. The same trap and the same fix apply to dictionaries and sets used as defaults. Numbers, strings and None are safe defaults, because they cannot be changed in place.
Try it yourself
Exercise 1: Greetings
Write greet(name, greeting="Hello") that returns a text such as Hello, Sara!. Call it three ways: with only a name, with a name and "Salaam", and with both as keyword arguments in reverse order.
Exercise 2: Average of anything
Write average(*numbers) that returns the average of any number of values, or 0 when there are none. Test it with 45, 78, 90, with no values, and with the list marks = [33, 61].
Exercise 3: Fix the trap
This function has the mutable default bug: def add_mark(mark, marks=[]). Write a fixed version, then give Ali the mark 78 and Sara the mark 90, add 61 to Ali’s list, and print both lists.
Solutions
Solution 1
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sara"))
print(greet("Omar", "Salaam"))
print(greet(greeting="Welcome", name="Hina"))
Hello, Sara!
Salaam, Omar!
Welcome, Hina!
The default fills in greeting only when it is missing; keywords can come in any order.
Solution 2
def average(*numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
print(average(45, 78, 90))
print(average())
marks = [33, 61]
print(average(*marks))
71.0
0
47.0
An empty tuple counts as false, so if not numbers catches the call with no values, and *marks unpacks the list.
Solution 3
def add_mark(mark, marks=None):
if marks is None:
marks = []
marks.append(mark)
return marks
ali = add_mark(78)
sara = add_mark(90)
add_mark(61, ali)
print(ali)
print(sara)
[78, 61]
[90]
Each call without a list makes a new one, so Ali and Sara do not share marks.
Common mistakes
- Using
[]or{}as a default. The same list is shared by every call, so data from one call shows up in the next. UseNoneand create the list inside. - Putting a default before a required parameter.
def order_line(name, quantity=1, price):givesSyntaxError: parameter without a default follows parameter with a default. - Positional after keyword in a call.
order_line(name="Pen", 60)givesSyntaxError: positional argument follows keyword argument. - **Passing a list to
*argswithout a star.**total(cart)sends one list, andsum()fails withTypeError: unsupported operand type(s) for +: 'int' and 'list'. Writetotal(*cart). - Misspelling a keyword.
qty=10instead ofquantity=10givesTypeError: order_line() got an unexpected keyword argument 'qty'.
Frequently asked questions
What are *args and **kwargs in Python?
They let a function accept any number of arguments. *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. Only the stars matter; args and kwargs are just the usual names.
Why are mutable default arguments bad in Python?
A default value is created once, when the function is defined, not on every call. If it is a list or dictionary and the function changes it, the change stays and appears in later calls. Use None as the default and create the list inside the function.
What is the difference between positional and keyword arguments?
A positional argument is matched to a parameter by its place in the call: the first value to the first parameter. A keyword argument is matched by name, like quantity=3, so its place does not matter. In one call, positional arguments must come first.
Summary
param=valuein thedefline gives a default; parameters with defaults go after required ones.- Keyword arguments pass values by name, in any order, but after all positional arguments.
*argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dict. In a call,*listand**dictunpack them.- Parameters after
*are keyword-only; parameters before/are positional-only. - A default is created once, so never use
[]or{}; useNoneand make a new one inside.
Next lesson
Next: Lesson 24, Python Variable Scope: LEGB, global and nonlocal.
Sources
- More Control Flow Tools: default values, keyword arguments, special parameters, arbitrary argument lists (Python tutorial)
- Compound statements: function definitions and default parameter values (Python language reference)
- Programming FAQ: why default values are shared, passing *args and **kwargs (Python docs)
- Glossary: argument and parameter (Python docs)
- Python downloads page (python.org)





