The Wayback Machine - https://web.archive.org/web/20240816094406/https://www.geeksforgeeks.org/use-mutable-default-value-as-an-argument-in-python/
Open In App

Use mutable default value as an argument in Python

Last Updated : 05 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 user interfaces that are more user-friendly and l
3 min read
How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num * num # call the function result = calculate_squa
3 min read
Why Python Uses 'Self' as Default Argument
Python, a versatile and widely used programming language, follows object-oriented principles in its design. One of the distinctive features of Python is the use of the keyword 'self' as a default argument in class methods. This choice plays a crucial role in maintaining the integrity of object-oriented programming (OOP) concepts and ensures proper
3 min read
Concept of Mutable Lists in Python
The concept of mutable lists refers to lists whose elements can be modified or changed after the list is created. In programming, a list is a data structure that stores an ordered collection of elements. The mutability of a list determines whether you can modify its contents, such as adding or removing elements, changing the values of existing elem
5 min read
Are Python Lists Mutable
Yes, Python lists are mutable. This means you can change their content without changing their identity. You can add, remove, or modify items in a list after it has been created. Here are some examples demonstrating the mutability of Python lists: Example 1: Creating List[GFGTABS] Python my_list = [1, 2, 3] my_list[1] = 20 # Change the second elemen
2 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definitions and statements. The sys module provides functi
3 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Python Lambda with underscore as an argument
In Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one number of arguments, but they contain only a single e
1 min read
Return the Angle of the Complex Argument in Radians in Python using NumPy
In this article, we are going to see how to return the angle of the complex argument in radians in Python Using NumPy. The NumPy library provides the numpy.angle() method to return the angle of the complex argument in radians in python. Let's look at the syntax of the method. Syntax: numpy.angle(z, deg=False) parameters: z: array like object. input
3 min read
Specify Argument Type For List of Dictionary For a Python
In this article, we will see how we can specify the argument type for a list of Dictionary for Python. As we know, Python is a dynamically typed language so the data type of a variable can change anytime. If a variable containing an integer may hold a string in the future, which can lead to Runtime Errors, Therefore knowing the data type of the arg
2 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call.is Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Keyword and Positional ArgumentKeyword-Only Argume
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 function. There are two types in Python: Non - Keyword
4 min read
How to Fix TypeError: String Argument Without an Encoding in Python
The TypeError: string argument without an encoding is a common error that arises when working with the string encoding in Python. This error typically occurs when attempting to the convert a string to the bytes without specifying the necessary encoding. In this article, we will explore the causes of this error and provide the practical solutions to
3 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name
5 min read
Command-Line Option and Argument Parsing using argparse in Python
Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module. Python Argparse ModuleThe 'argparse' module in Python hel
8 min read
Add new column with default value in PySpark dataframe
In this article, we are going to see how to add a new column with a default value in PySpark Dataframe. The three ways to add a column to PandPySpark as DataFrame with Default Value. Using pyspark.sql.DataFrame.withColumn(colName, col)Using pyspark.sql.DataFrame.select(*cols)Using pyspark.sql.SparkSession.sql(sqlQuery)Method 1: Using pyspark.sql.Da
3 min read
Set a Default Value for a Field in a Django Model
Django is a powerful web framework for building web applications in Python. One common task in Django is setting up models, which are classes that represent database tables. Sometimes, it's useful to have default values for certain fields in these models. This article will guide you through creating a small Django project, including setting a defau
4 min read
Django Form | Build in Fields Argument
We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of code. Although the developer has the option of des
3 min read
How to pass a list as a command-line argument with argparse?
Argparse is a Python library used to parse command-line arguments in a user-friendly manner. It makes it easy to write user-friendly command-line interfaces, and it is widely used in Python applications. In this tutorial, we will discuss how to pass a list as a command-line argument using the Argparse library in Python. Passing a List as a Command
5 min read
Python IMDbPY – Default info of Company object
In this article we will see how we can achieve the set of information which retrieved by default by get_company method, with the help of get_company_infoset we can know all the information that we can achieve of the company. But all the information is not extracted as it will be time consuming process. In order to know the default information that
1 min read
Python IMDbPY – Default info of Movie object
In this article we will see how we can achieve the set of information which retrieved by default by get_movie method, with the help of get_movie_infoset we can know all the information that we can achieve of the movie. But all the information is not extracted as it will be time consuming process. In order to know the default information that a movi
1 min read
Python IMDbPY – Default info of Person object
In this article we will see how we can achieve the set of information which retrieved by default by get_person method, with the help of get_person_infoset we can know all the information that we can achieve of the person. But all the information is not extracted as it will be time consuming process. In order to know the default information that a m
1 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 argument will take that value if no argument value is
7 min read
default - Django Built-in Field Validation
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value. The
3 min read
Setting python3 as Default in Linux
Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command 'python' on the terminal, interpreter of python2 gets laun
1 min read
wxPython - Get Default Attributes of StaticText
In this article, we are going to learn how can we get different attributes of StaticText like background, foreground colors, and fonts. We use GetClassDefaultAttributes() function to get an object of wx.VisualAttributes. It may or may not take variant as an argument. Syntax: wx.StaticText.GetClassDefaultAttributes() or wx.StaticText.GetClassDefault
1 min read
PyQt5 QCommandLinkButton - Setting Auto Default Property
In this article we will see how we can set the auto default property of the QCommandLinkButton. If this property is set to true then the command link button is an auto default button. In some GUI styles a default button is drawn with an extra frame around it, up to 3 pixels or more. Qt automatically keeps this space free around auto-default buttons
2 min read
PyQt5 QCommandLinkButton - Getting Auto Default Property
In this article we will see how we can get the auto default property of the QCommandLinkButton. If this property is set to true then the command link button is an auto default button. In some GUI styles a default button is drawn with an extra frame around it, up to 3 pixels or more. Qt automatically keeps this space free around auto-default buttons
2 min read
wxPython | Get default attributes of Radio Box
In this article we are going to learn about GetClassDefaultAttributes() function associated with wx.RadioBox class of wxPython. GetClassDefaultAttributes() function is used to return wx.VisualAttributes object for properties like background color, foreground color and font associated with Radio box. It takes variant as arguments. Syntax: wx.RadioBo
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg