Notes
Categories

Default Arguments in Python [ English ]

< Prev Next >

1. Introduction

Default arguments allow a function to be called without providing all the required parameters. By assigning a default value to a parameter, Python automatically uses that value when no argument is supplied during the function call.

This feature improves flexibility and reduces the need to pass repetitive values.


2. Definition

A default argument is a parameter that has a predefined value assigned in the function definition. If the caller does not provide a value for that parameter, the default value is used.


3. Syntax

def function_name(parameter = default_value):
    # code block

4. Basic Example

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

Function Calls:

greet("Alice")
greet()

Output:

Hello, Alice
Hello, Guest

5. Multiple Default Arguments

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

Calls:

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

Output:

9
27

6. Important Rules

6.1 Order of Parameters

Parameters with default values must come after non-default parameters.

✔ Correct:

def func(a, b=10):
    pass

✘ Incorrect:

def func(a=10, b):
    pass

6.2 Overriding Default Values

Default values can be overridden by passing arguments during the function call.

def show(price=100):
    print(price)

show()      # 100
show(250)   # 250

6.3 Mutable Default Arguments (Important Concept)

Using mutable objects (like lists or dictionaries) as default arguments can lead to unexpected behavior.

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

print(add_item(1))
print(add_item(2))

Output:

[1]
[1, 2]   # unexpected behavior

Reason: The same list is reused across function calls.

✔ Correct approach:

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

7. Advantages of Default Arguments


8. Key Insight

Default arguments are evaluated only once at the time of function definition, not each time the function is called. This is especially important when dealing with mutable data types.


9. Conclusion

Default arguments provide a convenient way to design flexible and user-friendly functions in Python. However, they must be used carefully, especially with mutable objects, to avoid unintended side effects.

< Prev Next >