CS Pathfinder Logo CS Pathfinder

Unit 3 · Functions

Default Arguments

Default arguments provide predefined values for function parameters, making them optional during the function call. Learn how to use default values, the rules governing their order, and the famous mutable default argument pitfall that catches even experienced developers.

Introduction

Sometimes, you want a function parameter to have a sensible default value so that the caller does not always need to provide it. For example, a greet() function might default to greeting "Guest" if no name is supplied.

Default arguments make this possible. You assign a value to the parameter in the function definition, and that value is used when the caller does not provide one.

Default arguments are extremely common in Python's built-in functions. For example, print() has default values for sep (space) and end (newline).

University Definition

A default argument is a parameter that has a predefined value in the function definition. If the caller does not provide a value for that parameter, the default value is used automatically. Default arguments make parameters optional.

Basic Example

def greet(name="Guest"):
    print("Hello,", name)

greet("Alice")    # Argument provided
greet()           # No argument — uses default
greet("Bob")      # Argument provided
Output:
Hello, Alice
Hello, Guest
Hello, Bob

Step-by-step:

  1. When you call greet("Alice"), name becomes "Alice".
  2. When you call greet(), no argument is passed, so name takes the default value "Guest".

Multiple Default Arguments

def student_info(name, age=18, city="Mumbai"):
    print(f"{name}, Age: {age}, City: {city}")

student_info("Alice")            # All defaults used for age & city
student_info("Bob", 22)          # Default city
student_info("Charlie", 20, "Delhi")  # No defaults used
Output:
Alice, Age: 18, City: Mumbai
Bob, Age: 22, City: Mumbai
Charlie, Age: 20, City: Delhi

The caller can choose which default arguments to override and which to leave as-is.

Order of Arguments in a Function Call

When a function has positional, default, and keyword arguments together, Python enforces this order:

Required Order:

def func(positional_args, default_args, *args, **kwargs):
       ^^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^
       Must come first     Must come after positional
# Correct order:
def display(name, age=18, city="Mumbai"):
    print(name, age, city)

display("Alice")                    # positional only
display("Bob", 22)                  # positional + default
display("Charlie", 20, "Delhi")    # positional + default overrides
display("Diana", city="Chennai")    # positional + keyword

Important Rule: Once a default parameter is defined, all parameters after it must also have defaults (unless using *args).

# WRONG — non-default after default
def func(a=10, b):    # SyntaxError: non-default argument follows default
    print(a, b)

Default Arguments in Built-in Functions

The print() function uses default arguments for sep and end:

# Default: sep=" " and end="\n"
print("Hello", "World")

# Custom sep
print("Hello", "World", sep="-")

# Custom end
print("Hello", end=" ")
print("World")
Output:
Hello World
Hello-World
Hello World

The Mutable Default Argument Pitfall

This is one of the most important traps in Python. Never use a mutable object (like a list or dictionary) as a default argument:

Danger Zone

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))
Unexpected Output:
['apple']
['apple', 'banana']
['apple', 'banana', 'cherry']

Most beginners expect three separate lists with one item each. Instead, the list keeps growing because the default list is created only once when the function is defined, and reused across all calls.

Correct Approach

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))
Correct Output:
['apple']
['banana']
['cherry']

Key Points

Default values make parameters optional.

Non-default parameters must come before default parameters.

Never use mutable objects (list, dict, set) as default values.

Use None as a sentinel for mutable defaults.

Default values are evaluated once at function definition time.

Built-in functions like print() use default arguments extensively.

University Exam Tip

Frequently asked exam questions:

  • What is a default argument in Python?
  • Can a non-default argument follow a default argument? Explain.
  • What is the mutable default argument problem? How do you avoid it?
  • Write a function with a default argument and demonstrate its usage.

Practice Questions

Q1. What is a default argument?

Answer: A default argument is a parameter with a predefined value in the function definition. If the caller does not provide a value, the default is used.

Q2. Why should you not use a list as a default argument?

Answer: Mutable default arguments are created once and shared across calls. This causes unexpected behavior where data from previous calls persists. Use None instead.

Q3. Write a function power(base, exp=2) that computes base raised to exp.

def power(base, exp=2):
    return base ** exp

print(power(3))      # 9 (uses default exp=2)
print(power(2, 10))  # 1024

Q4. Is the following valid? def func(a=1, b): pass

Answer: No. Non-default parameter b cannot follow default parameter a. This raises a SyntaxError.

Q5. What will be the output?

def func(x, lst=[]):
    lst.append(x)
    return lst

print(func(1))
print(func(2))
print(func(3, []))
Output:
[1]
[1, 2]
[3]

Summary

  • Default arguments provide fallback values for parameters.
  • Non-default parameters must come before default parameters.
  • Never use mutable objects as default arguments.
  • Use None as a sentinel value for mutable defaults.
  • Default values are evaluated once when the function is defined.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.