Defining Default Parameters in Python
Syntax for Default Parameters
To define a default parameter in a Python function, you simply need to assign a value to the parameter when declaring the function. The syntax is as follows:
def function_name(param1, param2=default_value):
## function body
pass
In the example above, param2
is the parameter with a default value. When calling the function, if the caller doesn't provide a value for param2
, the function will use the default_value
instead.
Placement of Default Parameters
When defining a function with multiple parameters, the default parameters should be placed after the required parameters. This ensures that the function can be called with the required parameters alone, without needing to provide values for the default parameters.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") ## Output: Hello, Alice!
greet("Bob", "Hi") ## Output: Hi, Bob!
In the example above, the name
parameter is required, while the greeting
parameter has a default value of "Hello"
.
Modifying Default Parameter Values
It's important to note that default parameter values are evaluated when the function is defined, not when it's called. This means that if you use a mutable object (like a list or a dictionary) as a default parameter, the same object will be shared across all function calls, which can lead to unexpected behavior.
def append_to_list(item, my_list=[]):
my_list.append(item)
return my_list
print(append_to_list("apple")) ## Output: ['apple']
print(append_to_list("banana")) ## Output: ['apple', 'banana']
print(append_to_list("cherry", [])) ## Output: ['cherry']
print(append_to_list("durian")) ## Output: ['apple', 'banana', 'durian']
To avoid this issue, it's recommended to use immutable objects (like None
) or to initialize the default parameter value to None
and create a new object inside the function.
By understanding the syntax, placement, and considerations around defining default parameters in Python, you can write more flexible and user-friendly functions that cater to a variety of use cases.