[PYTHON] Precautions when using a list or dictionary as the default argument

Note that lists and dictionaries are passed by reference

def test_func(x, l=[]):
    l.append(x)
    return l


r = test_func(100)
print(r)

r = test_func(100)
print(r)

I should have made an empty list as the default argument ...

[100]
[100, 100]

To improve, do the following

def test_func(x, l=None):
    if l is None:
        l = []
    l.append(x)
    return l


r = test_func(100)
print(r)

r = test_func(100)
print(r)

output:

[100]
[100]

Recommended Posts

Precautions when using a list or dictionary as the default argument
Extract the value of dict or list as a string
Precautions when using the urllib.parse.quote function
If you give a list with the default argument of the function ...
Use the e-paper module as a to-do list
Isn't there a default value in the dictionary?
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
I checked the reference speed when using python list, dictionary, and set type in.
A simple difference when passing a pointer as a function argument
Precautions when using Chainer
Creating a list when the nomenclature is a fixed time
Create a dictionary by searching the table using sqlalchemy
The story I was addicted to when I specified nil as a function argument in Go
Problems when using Elasticsearch as a data source in Redash
How to put the string JSON passed as a parameter into the dictionary when writing Ansible module
Be careful when specifying the default argument value in Python3 series
Precautions when creating a two-dimensional array with all the same values
The story that a hash error came out when using Pipenv
Utilization of lambda (when passing a function as an argument of another function)
Try using Elasticsearch as the foundation of a question answering system
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
The story of making a slackbot that outputs as gif or png when you send the processing code
A memorandum when using beautiful soup
Precautions when using pit in Python
Precautions when inheriting the DatasetMixin class
Precautions when using TextBlob trait analysis
Create a nested dictionary using defaultdict
Precautions when using codecs and pandas
Precautions when creating a Python generator
When creating a matrix in a list
Precautions when using phantomjs from python
Precautions when using six with Python 2.5
Push the hash list into VT and receive the detection result as a list
A useful note when using Python for the first time in a while