← Back to Articles
Tutorial

Understanding Python Default Arguments

Learn how to use Python default arguments to write cleaner and more efficient code.

Python default arguments are a feature that allows functions to have pre-determined values for certain parameters. This can make functions more flexible and easier to use, as it allows function callers to omit certain arguments when they aren't needed.

When defining a function, you can specify default values for parameters by assigning them a value in the function definition. For example, in the function `def greet(name, greeting='Hello')`, `greeting` has a default value of 'Hello'. If the caller does not provide a value for `greeting`, it will default to 'Hello'.

To effectively use default arguments, place them after any non-default arguments in your function definition. This practice ensures clarity and prevents syntax errors. Additionally, default arguments can be any immutable data type such as numbers, strings, or tuples.

A common mistake is using mutable default arguments like lists or dictionaries. Since default arguments are evaluated once at function definition, using mutable types can lead to unexpected behavior if the object is modified. Always use immutable types for default arguments to avoid these pitfalls.

Code Examples

Example 1

def add(a, b=5):
    return a + b

result = add(3)
print(result)  # Output: 8

Example 2

def greet(name, greeting='Hello'):
    return f'{greeting}, {name}!'

message = greet('Alice')
print(message)  # Output: Hello, Alice!

More Python Tutorials