Skip to content

Module 9 · Functions — topic 8 of 19

Default arguments

Giving parameters default values so callers can omit them, the rule that defaults are evaluated once, and the mutable-default trap with its None-based fix.

Beginner 10 min read·Lesson 133 of 306 in Python Programming

Learning objectives

  • Define functions with optional parameters
  • Explain when default values are evaluated
  • Avoid the mutable default argument bug

Definition

A default argument value is specified in the function definition as parameter=value; if the caller doesn't supply that argument, the parameter takes the default.

Introduction

round(3.14159) and round(3.14159, 2) both work because ndigits has a default. Defaults let one function serve the common case simply and the special case flexibly.

Why it matters

Defaults keep calls short. But they hide one of Python's most famous traps: a default list or dict is created once and shared by every call.

Detailed explanation

Parameters with defaults must come after parameters without them: def f(a, b=1) is valid; def f(a=1, b) is a SyntaxError.

Default values are evaluated once, when the def statement runs — not on every call.

For immutable defaults (numbers, strings, None, tuples) this doesn't matter. For mutable defaults (lists, dicts, sets), every call that relies on the default shares the same object, so changes persist between calls.

The fix is to use None as the default and create a fresh object inside: def add(item, items=None): if items is None: items = [].

Defaults also make functions backward compatible: adding a new optional parameter doesn't break existing calls.

Syntax

Python
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
  • Defaults come after required parameters.
  • They are evaluated once, at definition.
  • Use None for mutable defaults.

Code examples

Optional parameters

Python
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
print(greet("Asha"))
print(greet("Ravi", "Welcome"))
print(greet("Meera", punctuation="?"))
Output
Hello, Asha!
Welcome, Ravi!
Hello, Meera?

The mutable default trap

Python
def add_tag_bad(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag_bad("python"))
print(add_tag_bad("java")) # the same list again!
Output
['python']
['python', 'java']

More examples

Fixing it with None

Python
def add_tag(tag, tags=None):
if tags is None:
tags = [] # a new list on every call
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("java"))
mine = ["sql"]
print(add_tag("git", mine), mine)
import time
def stamp(when=time.strftime("%Y")): # evaluated once, at definition
return when
print(stamp() == stamp())
Output
['python']
['java']
['sql', 'git'] ['sql', 'git']
True

Step-by-step explanation

  • With tags=None, each call that omits tags creates its own empty list.
  • Passing an existing list still works and appends to that list.
  • stamp's default is computed once when def runs, so every call returns the same value — the same reason the list default was shared.

Expected output

Running “Fixing it with None” prints exactly:

TextOutput
['python']
['java']
['sql', 'git'] ['sql', 'git']
True

Practical applications

  • open(path, mode="r", encoding=None) and many standard functions use defaults.
  • Code reviewers routinely flag mutable defaults.

Best practices

  • Use immutable defaults; use None for 'create a new one'.
  • Put the most commonly changed optional parameters first, or make them keyword-only.
  • Document what a default means.

Common mistakes

Mutable default

Avoid

def register(user, users=[]): ...

Prefer

def register(user, users=None):
if users is None:
users = []

The default list is created once and shared by all calls.

Default before required

Avoid

def f(a=1, b): ...

Prefer

def f(b, a=1): ...

Parameters without defaults must come first (SyntaxError otherwise).

Important notes

  • Linters such as pylint warn about dangerous mutable defaults (W0102).

Key takeaways

  • Defaults make parameters optional.
  • Default values are evaluated once, at definition time.
  • Never use a mutable object as a default; use None.

Try it yourself

  1. 1
    Write format_price(amount, currency="Rs", decimals=2) and call it three ways.
  2. 2
    Write a function that collects log messages, fixing the mutable default bug.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
Practise this topic