[PYTHON] If you give a list with the default argument of the function ...

1


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

y = [1, 2, 3, 4]
r = test(7, y)
print(r)

Execution result of 1


[1, 2, 3, 4, 7]

2


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

r = test(100)
print(r)
r = test(100)
print(r)

Execution result of 2


[100]
[100, 100]

I intended to do the same process twice, The second time, 100 becomes two.

This happens because the list is passed by reference. Because it often leads to bugs Do not pass by reference, such as lists and dictionaries, as default arguments.

So write as follows.

3


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

y = [1, 2, 3, 4]
r = test(7, y)
print(r)

r = test(100)
print(r)
r = test(100)
print(r)

Execution result of 3


[1, 2, 3, 4, 7]
[100]
[100]

Recommended Posts

If you give a list with the default argument of the function ...
Find the optimal value of a function with a genetic algorithm (Part 2)
Precautions when using a list or dictionary as the default argument
Make the default value of the argument immutable
If you want a singleton in python, think of the module as a singleton
Have Alexa run Python to give you a sense of the future
Generate a list packed with the number of days in the current month.
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Receive a list of the results of parallel processing in Python with starmap
Get the caller of a function in Python
Make a copy of the list in Python
Get a list of IAM users with Boto3
Fix the argument of the function used in map
If you guys in the scope kitchen can do it with a margin ~ ♪
How to get a list of files in the same directory with python
[Python] Wouldn't it be the best and highest if you could grasp the characteristics of a company with nlplot?
Do not specify a mutable object (list type, dictionary type, etc.) as the initial value of the function argument of python.
If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
Make a note of the list of basic Pandas usage
# Function that returns the character code of a string
Make the default value of the argument immutable (article explanation)
Visualize the characteristic vocabulary of a document with D3.js
I examined the argument class_weight of Chainer's softmax_cross_entropy function.
How to check in Python if one of the elements of a list is in another list
Calculate the product of matrices with a character expression?
The value of meta when specifying a function with no return value in Dask dataframe apply
Make a note of what you want to do in the future with Raspberry Pi
Give the history command a date and time and collect the history files of all users with a script
If you want to put an argument in the closure function and execute it later
If you draw an Omikuji with a probability of 1% 100 times in a row, will you win once?
Try to get the function list of Python> os package
A network diagram was created with the data of COVID-19.
Measure the importance of features with a random forest tool
Get the number of specific elements in a python list
Get a list of purchased DMM eBooks with Python + Selenium
Check the scope of local variables with the Python locals function.
I made a function to check the model of DCGAN
[Python3] Call by dynamically specifying the keyword argument of the function
How to display a list of installable versions with pyenv
I tried a little bit of the behavior of the zip function
Extract the value of dict or list as a string
Analyze the topic model of becoming a novelist with GensimPy3
2015-11-26 python> Display the function list of the module> import math> dir (math)
The story of making a question box bot with discord.py
How to connect the contents of a list into a string
[Django] What to do if the model you want to create has a large number of fields
When I try to divide a list with MeCab, I get'TypeError: in method'Tagger_parse', argument 2 of type'char const *''
A decorator that notifies you via AWS-SNS if the function does not finish within the specified time
Let's prove the addition theorem of trigonometric functions by replacing the function with a function in SymPy (≠ substitution)
Process the contents of the file in order with a shell script
A story stuck with the installation of the machine learning library JAX
If you want to become a data scientist, start with Kaggle
If you know Python, you can make a web application with Django
Get the number of PVs of Qiita articles you posted with API
Save the result of the life game as a gif with python
I tried to get the index of the list using the enumerate function
[Statistics] Grasp the image of the central limit theorem with a graph
[python, ruby] fetch the contents of a web page with selenium-webdriver
[Introduction to Python] How to split a character string with the split function