Python Positional, Keyword, and Default Arguments
Python functions can receive values by position, by name, or from defaults when you leave an argument out. Positional arguments depend on order, keyword arguments depend on the parameter name, and default arguments provide a built-in value when no argument is supplied. This article shows how they work together, where people get confused, and how to avoid the common mistakes.
Difficulty: Beginner
Helpful to know first: basic Python syntax, how to define a function, and what variables store.
How Python Matches Arguments to Parameters
When you call a function, Python matches the values you pass to the function’s parameters. A parameter is the name in the function definition, and an argument is the value you pass in the call.
Python has three common ways to supply arguments:
- Positional arguments are matched by order.
- Keyword arguments are matched by name.
- Default arguments are used when you do not pass a value for that parameter.
The simplest example uses only positional arguments:
def greet(name, message):
print(name, message)
greet("Ava", "welcome")
# Output: Ava welcomePython assigns "Ava" to name and "welcome" to message because that is the order in the function call. If you swap the order, the meaning changes too.
Using Positional Arguments When Order Matters
Positional arguments are the most direct way to call a function. They are often used when the meaning is obvious from the order or when a function is short.
A simple calculation
Here the function subtracts the second number from the first. The order matters, so positional arguments are a good fit.
def difference(first, second):
print(first - second)
difference(10, 3)
# Output: 7If you change the order, you get a different answer:
def difference(first, second):
print(first - second)
difference(3, 10)
# Output: -7That is the main strength of positional arguments: they are concise. Their weakness is that the order must be correct, or the call means something else.
When positional arguments are easy to read
Some functions are clearer when the order is standard and familiar. A common example is using a function to format a rectangle or a point:
def area(width, height):
print(width * height)
area(4, 5)
# Output: 20Because the function name and the parameter order make sense together, the call stays short and readable.
Using Keyword Arguments for Clarity
Keyword arguments name the parameter directly in the call. This makes the code easier to read, and it lets you pass arguments in any order.
Calling the same function by name
Keyword arguments are useful when a function has more than two parameters or when the order is not obvious.
def greet(name, message):
print(name, message)
greet(message="hello", name="Ava")
# Output: Ava helloNotice that the arguments are written in the opposite order from the parameters, but Python still matches them correctly by name.
Why keyword arguments reduce mistakes
Suppose a function uses several numbers that are easy to mix up. Keyword arguments make the call self-documenting.
def create_account(username, age, active):
print(username, age, active)
create_account(active=True, username="maya", age=19)
# Output: maya 19 TrueThe reader does not need to remember the parameter order to understand the call. That is especially helpful when a function has many arguments.
Using Default Arguments to Make Parameters Optional
A default argument gives a parameter a fallback value. If the caller omits that argument, Python uses the default from the function definition.
Providing a fallback value
Here the punctuation parameter defaults to a period.
def say(text, punctuation="."):
print(text + punctuation)
say("Hello")
say("Hello", "!")
# Output:
# Hello.
# Hello!The first call uses the default value. The second call overrides it with an explicit argument.
Defaults make functions easier to use
Defaults are useful when a value is common but not always necessary.
def repeat(word, times=2):
print(word * times)
repeat("ha")
repeat("ha", 4)
# Output:
# haha
# hahahahaWithout the default, every call would need the same value repeated even when the common case is obvious.
How Positional, Keyword, and Default Arguments Work Together
These three ideas are not separate rules. They work together in one function call. Python first matches positional arguments from left to right, then matches keyword arguments by name, and finally fills in any missing parameters that have defaults.
A function definition can mix required parameters and optional parameters:
def introduce(name, city="unknown", emoji="🙂"):
print(name, "from", city, emoji)
introduce("Kai")
introduce("Kai", "Tokyo")
introduce("Kai", emoji="👋")
# Output:
# Kai from unknown 🙂
# Kai from Tokyo 🙂
# Kai from unknown 👋This example shows all three behaviors:
- name is required.
- city and emoji have defaults.
- A keyword argument can replace only one default while leaving the others alone.
How Python Behaves in Detail
Python does not guess what you meant. It follows a specific matching order and raises an error if the call does not fit the function definition.
Positional arguments must come before keyword arguments in a call
Once you start using keyword arguments in a function call, all later arguments must also be keyword arguments unless the function is designed for special parameter types. This rule prevents ambiguity.
def show(a, b, c):
print(a, b, c)
show(1, b=2, 3)
# SyntaxError: positional argument follows keyword argumentThe call is invalid because Python cannot place the final positional value after a keyword argument. The fix is to make the whole call positional or move the remaining value into a keyword argument if the function allows it.
Keyword arguments must use a valid parameter name
If you misspell a keyword, Python treats it as an unexpected keyword argument.
def greet(name):
print(name)
greet(nmae="Ava")
# TypeError: greet() got an unexpected keyword argument 'nmae'Python does not correct the spelling for you. The keyword must match the parameter name exactly.
Defaults are evaluated once, when the function is defined
This is one of the most important details about default arguments in Python. A default value is created when Python executes the def statement, not each time the function runs.
def increment(value=0):
value += 1
print(value)
increment()
increment()
# Output:
# 1
# 1For immutable values like numbers and strings, this is usually harmless. The bigger problem appears with mutable defaults such as lists, which the next section covers.
Predict the Output
Question 1: keyword arguments and order
What does this print?
def paint(color, shape):
print(shape, color)
paint(shape="circle", color="blue")Show answer
The function prints circle blue. Keyword arguments are matched by name, not by order. Python puts "circle" into shape and "blue" into color.
Question 2: default arguments and reassignment
What happens here?
def add_one(n=5):
n += 1
print(n)
add_one()
add_one()Show answer
It prints 6 and then 6 again. The default value 5 is reused, but the function only rebinds the local name n. It does not change the stored default value.
Common Mistakes with Function Arguments
Forgetting the correct order for required and default parameters
In a function definition, a parameter with a default value cannot come before a required parameter. Python needs a clear rule for how to fill missing values.
Problem: This definition is invalid because a required parameter follows a default parameter, so Python cannot tell whether the second argument was omitted or intended for the later parameter.
def bad_order(name="Ava", age):
print(name, age)Fix: Put required parameters first, then optional ones with defaults.
def good_order(age, name="Ava"):
print(name, age)
good_order(20)
# Output: Ava 20The corrected version works because Python can always assign the first value to age and use the default for name when needed.
Using a mutable object as a default value
Lists, dictionaries, and sets are mutable, which means they can change in place. If you use one as a default argument, the same object is reused across calls.
Problem: This function keeps the same list between calls, so the second call sees the value added by the first call.
def append_item(item, items=[]):
items.append(item)
print(items)
append_item(1)
append_item(2)
# Output:
# [1]
# [1, 2]Fix: Use None as the default and create a new list inside the function.
def append_item(item, items=None):
if items is None:
items = []
items.append(item)
print(items)
append_item(1)
append_item(2)
# Output:
# [1]
# [2]The corrected version works because each call gets a fresh list when no list is passed in.
Passing the wrong number of arguments
If you pass too many or too few values, Python raises an error because the call does not match the function signature.
Problem: This call leaves out a required argument, so Python cannot fill every parameter.
def move(x, y):
print(x, y)
move(10)
# TypeError: move() missing 1 required positional argument: 'y'Fix: Pass the missing value or give the parameter a default if it should be optional.
def move(x, y=0):
print(x, y)
move(10)
# Output: 10 0The fixed version works because y now has a default value.
Find the Bug
Find the subtle bug in this function. It looks reasonable, but it does not behave the way the author probably intended.
def add_tag(tag, tags=[]):
tags.append(tag)
print(tags)
add_tag("python")
add_tag("functions")Show answer
The bug is the mutable default list. Python creates one list when the function is defined and reuses it for every call that omits tags. That means the second call prints both items instead of starting over.
Fixed code:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
print(tags)
add_tag("python")
add_tag("functions")
# Output:
# ['python']
# ['functions']The fix works because a new list is created inside the function each time the caller does not pass one.
When to Use Positional, Keyword, and Default Arguments
These argument styles solve different problems, and many functions use more than one at once.
| Style | Best for | Strength | Trade-off |
|---|---|---|---|
| Positional arguments | Short calls where order is obvious | Concise | Easy to mix up when there are many parameters |
| Keyword arguments | Readable calls and functions with many options | Clearer meaning | More typing |
| Default arguments | Optional values with common fallbacks | Fewer required inputs | Can be misused with mutable values |
Use positional arguments when the order is obvious and the function stays small. Use keyword arguments when readability matters more than brevity. Use default arguments when a parameter is optional, but make sure the default is safe and sensible.
Python also has two related ideas that often appear in more advanced code:
- *args collects extra positional arguments into a tuple.
- **kwargs collects extra keyword arguments into a dictionary.
Those features are useful in decorators, wrappers, and APIs, but they are separate from the basic positional, keyword, and default argument rules covered here.
Predict the Output
Question 1: changing the same list across calls
What does this print?
def collect(item, items=[]):
items.append(item)
print(items)
collect(1)
collect(2)Show answer
It prints [1] and then [1, 2]. The same list object is reused because default values are created once, not on every call.
Question 2: positional vs keyword matching
What happens here?
def mix(a, b, c=3):
print(a, b, c)
mix(1, 2, c=10)Show answer
It prints 1 2 10. The first two arguments fill a and b by position, and the keyword argument replaces the default for c.
Summary
- Positional arguments are matched by order.
- Keyword arguments are matched by parameter name and can be passed in any order.
- Default arguments supply a value when the caller omits a parameter.
- Python matches positional arguments first, then keyword arguments, then fills in defaults.
- Default values are evaluated once when the function is defined, which is why mutable defaults can be dangerous.
- Put required parameters before optional ones in a function definition.
Next, learn how *args and **kwargs let you accept a variable number of positional and keyword arguments.