Electron microscopy
 
PythonML
Default Mutable Argument
- Python Automation and Machine Learning for ICs -
- An Online Book -
Python Automation and Machine Learning for ICs                                                           http://www.globalsino.com/ICs/        


Chapter/Index: Introduction | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | Appendix

=================================================================================

In Python, a default mutable argument refers to a situation where a mutable object (such as a list or dictionary) is used as a default value for a function parameter. This can lead to unexpected behavior if the mutable object is modified within the function. 

An example using a list as a default argument is given by code,

 

   Output: 

 

In the example above, the add_element function has a default argument my_list with a default value of an empty list []. If we call the function without providing a value for my_list, it uses the default empty list. However, because lists are mutable, the modifications made to my_list persist across function calls. In the above example, when add_element(1) is called, it appends 1 to the default list. When add_element(2) is called later, it continues to use the modified list, and the result is [1, 2]. This behavior might not be what we expect.

To avoid this issue, it's recommended to use immutable objects (like None) as default values and then initialize the mutable object inside the function if needed, for instance, code:  

 

   Output: 

 

The code above shows that by using None as the default value and creating a new list inside the function when needed, wecan avoid unexpected behavior related to default mutable arguments in Python. 

============================================

         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         

 

 

 

 

 



















































 

 

 

 

 

=================================================================================