Skip to main content

How to Set Default Argument Values in Python Functions

How to Set Default Argument Values in Python Functions | Rustcode

How to Set Default Argument Values in Python Functions

Default arguments allow Python functions to be more flexible: you can specify default values for parameters so callers can skip them if they want. This makes code more concise and user-friendly for many use-cases. Let’s break down the concept, show key syntax, highlight best practices, and reveal some important pitfalls.


Why Use Default Arguments?

  • Simplicity: Makes common function calls shorter and easier to write.
  • Flexibility: Allows optional parameters & overloads behavior.
  • Backward Compatibility: You can safely add new parameters without breaking older calls.

Syntax for Default Arguments

Set default values using the = operator in the function definition. Defaulted parameters must come after non-defaulted ones.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")
greet("Bob", "Hi")

Output

Hello, Alice!
Hi, Bob!
  • If you don't pass an argument, Python uses the defined default.
  • Default parameters can be of any immutable type (int, str, tuple, etc.).

Examples: Using Default Values

# Default in the last parameter
def power(base, exponent=2):
    return base ** exponent

print(power(4))       # uses default exponent
print(power(4, 3))    # overrides default

# Multiple defaults
def info(first, last="Smith", grade="A"):
    print(f"{first} {last}, Grade: {grade}")

info("Tim")
info("Lucy", grade="B")
info("Raj", "Kumar", "C")

Output

16
64
Tim Smith, Grade: A
Lucy Smith, Grade: B
Raj Kumar, Grade: C
  • Defaults can be overridden with positional or keyword arguments.

Multiple Defaults & Argument Order

All required (non-default) arguments must come before any arguments with default values.

def func(a, b=5, c=10):
    return a + b + c

print(func(1))
print(func(1, 2, 3))

# def wrong_func(a=1, b):  # ❌ Not allowed! (SyntaxError)
#     return a + b

Output

16
6
  • Python will raise a SyntaxError if you put a default argument before a required one.

Beware: Mutable Default Pitfall

Danger: Default argument values are evaluated once, at function definition time—not each time the function runs. If you use a mutable object (like list or dict), that same object is reused across calls—often causing bugs!
def append_item(item, item_list=[]):
    item_list.append(item)
    return item_list

print(append_item('a'))
print(append_item('b'))  # Problem! Expected ['b']

# Correct pattern:
def safe_append(item, item_list=None):
    if item_list is None:
        item_list = []
    item_list.append(item)
    return item_list

print(safe_append('a'))
print(safe_append('b'))

Output

['a']
['a', 'b']
['a']
['b']
  • Immutable defaults (int, str, None) are safe. Avoid using lists, dicts, or custom objects as defaults unless you specifically want the same object reused between calls.

Quick Reference Table

Usage Syntax / Result When to Use
Single default argument def f(a, b=2): ... Common optional flags/params
Multiple defaults def f(a, b=2, c=3): ... Default configs, overloads
Mix of required + defaults def f(a, b, c=2): ... Some args always needed
Keyword override f(a=1, c=5) Override just a few params
Mutable default fix def f(a=None): ... Lists, dicts, custom objects

Useful Tips

  • Use None as a default for mutable types, then assign inside the function if needed.
  • Prefer immutable types (such as int, str, tuple) as default arguments.
  • Default arguments improve API usability—document them clearly.
  • Avoid placing required arguments after ones with defaults—this leads to errors.
  • Default values are evaluated only once when the function is defined, not on each function call.

Conclusion

Setting default argument values in Python functions is a powerful feature that leads to more flexible and maintainable code. Always watch out for the mutable default gotcha, and keep your APIs user-friendly by thoughtfully choosing which arguments to make optional!

Comments