Use mutable default value as an argument in Python
Last Updated :
05 Jun, 2023
Python lets you set default values for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those modifications will persist across function calls.
However, using mutable default values as arguments in Python can lead to unexpected behavior. This article explores the concept of volatile defaults, the potential problems they can cause, and how to use them effectively.
Understanding Mutable and Immutable Values in Python
Before going into the topic, let us get an overview of what mutable and immutable objects are from the perspective of Python.
Mutable Value in Python
Mutable values are the values that can be modified after being created. This implies that you can modify the values without producing a new value. Below is an illustration of mutable and immutable values implemented in Python.
Example:
Python3
# Python mutable value (List)
demo_list = [1, 2, 3, 4, 5]
print("Original List:", demo_list)
demo_list[0] = 10
print("Modified List:", demo_list)
Output:
Original List: [1, 2, 3, 4, 5]
Modified List: [10, 2, 3, 4, 5]
Immutable Value in Python
Contrary to mutable values in Python, there is an immutable value that cannot be edited or modified as shown below:
Example:
Python3
# Python immutable values (Tuple)
demo_tuple = (1, 2, 3, 4, 5)
print("Original Tuple", demo_tuple)
demo_tuple[0] = 10
print("Modified Tuple", demo_tuple)
Output:
What are Mutable Default Values
Now that we know what a mutable value is in Python and when we use such mutable values as default values for parameters when defining a function in Python it is called a mutable default value.
Example:
Python3
# Python function with mutable default value
def append_to(element, arr=[]):
arr.append(element)
return arr
# calling the function
print(append_to(12))
print(append_to(42))
print(append_to(99))
Output:
As you can see, the above function takes in 2 parameters first `element` value which is a compulsory argument, and the second one `arr` with a default value of an empty list. If we call this function by passing only a single argument means no argument for `arr`, it will use the default value that is an empty list.
[12]
[12, 42]
[12, 42, 99]
As you can see the same list is used whenever we call the function with a single argument, this is because the default value list is modified each time the function is called.
Problems of Using Mutable Default Values
Mutable default values are quite a useful feature provided in Python but they can cause unexpected behavior if not used carefully. Consider the case of the above example where we ended up appending all values to a single list when the function was called only with a single argument.
Now consider calling the function again with both the 2 expected arguments.
Example:
Python3
# Python function with mutable default value
def append_to(element, arr=[]):
arr.append(element)
return arr
# calling the function
print(append_to(12))
print(append_to(42))
print(append_to(99))
# calling the function with two arguments
print(append_to(101, [1, 2, 3]))
Output:
[12]
[12, 42]
[12, 42, 99]
[1, 2, 3, 101]
The above output is expected by the function definition. It seems the function is working correctly. However, let's call the function one more time without passing `arr` to it and see the output.
Example:
Python3
# Python function with mutable default value
def append_to(element, arr=[]):
arr.append(element)
return arr
# calling the function with one argument
print(append_to(12))
print(append_to(42))
print(append_to(99))
# calling the function with two arguments
print(append_to(101, [1, 2, 3]))
# unexpected output
print(append_to(102))
Output:
In this example, there is something very important to notice in the last function call output. Instead of creating a new empty list as expected due to the default value in the function definition, it continues to append the values in the previous list.
[12]
[12, 42]
[12, 42, 99]
[1, 2, 3, 101]
[12, 42, 99, 102]
This behavior is unexpected and can lead to bugs that are difficult to find and debug.
Recommended Way to Use Mutable Default Value
In the above section, we have explained the problems with the above approach now let's see the recommended method to use a mutable default value to avoid mentioned problems. Following is the modified code in which we used recommended way to use the mutable default value.
Example:
Python3
# recommended way to use mutable default values in Python
def append_to(element, arr=None):
if arr is None:
arr = []
arr.append(element)
return arr
# calling the function with one argument
print(append_to(12))
print(append_to(42))
print(append_to(99))
# calling the function with two arguments
print(append_to(101, [1, 2, 3]))
# calling the function with one argument again
print(append_to(102))
Output:
In the above code, we have used 'None' as the default value instead of an empty list. With this modification, calling the `append_to` function without passing a value for `arr` will always create a new empty list and append the element value into that newly created list.
[12]
[42]
[99]
[1, 2, 3, 101]
[102]
Similar Reads
Least Astonishment and the Mutable Default Argument in Python
The principle of Least Astonishment (also known as least surprise) is a design guideline that states that a system should behave the way it is intended to behave. It should not change its behavior in an unexpected manner to astonish the user. By following this principle, designers can help to create
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure.Example:Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Set instance attribute s
3 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argum
7 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read
Tuple as function arguments in Python
Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different c
2 min read
How to set default arguments in Ruby?
Setting default arguments in Ruby allows you to define values that will be used when no argument is provided for a method parameter. This feature provides flexibility and enhances code readability. Let's explore various approaches to set default arguments in Ruby: Table of Content Approach 1: Using
3 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python
4 min read
Variable Length Argument in Python
In this article, we will cover about Variable Length Arguments in Python. Variable-length arguments refer to a feature that allows a function to accept a variable number of arguments in Python. It is also known as the argument that can also accept an unlimited amount of data as input inside the func
4 min read
Python - Passing list as an argumnet
When we pass a list as an argument to a function in Python, it allows the function to access, process, and modify the elements of the list. In this article, we will see How to pass a list as an argument in Python, along with different use cases. We can directly pass a list as a function argument.Pyt
2 min read
Can Named Arguments Be Used with Python Enums?
Enums (Enumerations) are a symbolic representation of a set of named values, commonly used in programming to define a collection of constants. In Python, Enums are used to organize sets of related constants in a more readable and maintainable way. Using named arguments with enums can enhance clarity
3 min read