In Python, function arguments can have default value. If a function, that already has a default value, is called without the argument then the default value is used otherwise the passed value overrides the default value.
Default arguments in Python function example
In the function display_message() one of the argument has a default value. While calling the function you can chose not to pass that argument, in that case default value is used.
def display_message(name, msg='Hi '): print(msg + name) display_message("Tom")
Output
Hi Tom
If you pass value for the default argument then the passed value is used rather than the default value.
def display_message(name, msg='Hi '): print(msg + name) display_message("Tom", "Hello Sir ")
Output
Hello Sir Tom
Restriction while using default arguments
A Python function can have a mix of both regular arguments and default arguments but regular arguments can’t be placed after a default argument, that results in an error.
def display_message(name, msg='Hi ', task): print(msg + name) def display_message(name, msg='Hi ', task):
Output
SyntaxError: non-default argument follows default argument
Default parameter values are evaluated in the beginning
Default parameter values are evaluated when the function definition is executed. This means that the default arguments are evaluated only once, when the function is defined and the same pre-computed value is used for each call.
This may give you unexpected results if default parameter is a mutable object, such as a list or a dictionary. Consider the following example where name argument has an empty list as default value.
def append_list(element, name=[]): name.append(element) return name name_list = append_list("Tom") print(name_list) other_list = append_list("Ryan") print(other_list)
Output
['Tom'] ['Tom', 'Ryan']
If you were expecting default argument to create a new list in each function call that won’t happen as the new list is created when the function is defined and the same default value is used in each call thereafter.
A way around this is to use None as the default, and explicitly test for it in the body of the function to create a new object each time function is called.
def append_list(element, name=None): if name is None: name = [] name.append(element) return name name_list = append_list("Tom") print(name_list) other_list = append_list("Ryan") print(other_list)
Output
['Tom'] ['Ryan']
That's all for this topic Default Arguments in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-