As pointed out in the comments, there is no passing by reference in Python in the first place. Refer to the following article. https://qiita.com/raccy/items/d4c5e7995a8fc90109ee#_reference-de4299be58ab9d936fcb
There are some inaccuracies in this article, partly because I wrote it when I was clearly lacking in understanding, but I would like to leave it as a memo of how I faced the questions I had at that time (leave a memo). May not be good).
When I first started python, the first thing I stumbled upon was the mysterious explanation that is often found everywhere: "All python arguments are passed by reference." I somehow understood the passing by reference. However, when I run the following code in python, ...
>>> a=1
>>> b=a
>>> b=2
>>> print(a,b)
1,2
Will be. Well, I think it's natural, but I'm not convinced if it's passed by reference (it seems natural that I wasn't convinced because it wasn't passed by reference in the first place). Because if you pass by reference
>>> a=1
>>> b=a
>>> b=2
>>> print(a,b)
2,2
Because it should be (this understanding at that time seems to have been correct). I was thinking, "If b = a by reference, then if both b and a share the same memory and b is rewritten, then a will also be rewritten." In fact, doing something similar in list does.
>>> a=[1,2,3]
>>> b=a
>>> b[0]=5
>>> print(a,b)
#[5,1,2],[5,1,2]
If it is passed by reference, it will be the behavior. That is, the ones that can contain multiple elements are passed by reference, and I wondered if only the numeric type is different, and when I check the memory locations of a and b with the following code, ...
>>> a=1
>>> b=a
>>> print(id(a)==id(b))
True
>>> b=2
>>> print(id(a)==id(b))
False
Therefore, when b = a, both b and a refer to the same place. However, if b = 2, b will refer to the location of the newly created int object with the value 2. On the other hand, a continues to refer to the original location. I understand. But this time, the list example is more confusing. So, when I look it up
>>> a=[1,2,3]
>>> b=a
>>> a_0=a[0]
>>> b[0]=5
>>> print(a[0])
5
>>> print(id(a)==id(b))
True
>>> print(id(a[0])==id(a_0))
False
>>> b=[4,5,6]
>>> print(id(a)==id(b))
False
I'm finally convinced with this. In other words.
I wrote it for a long time, that is, When the new object itself is assigned to the __ variable, it will refer to the place where the new object was created instead of the previous reference destination. __ There should be no problem in practice.
Recommended Posts