Let's take a note again. I made a 3x3 2D list.
# Like this
print(tmp)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
So, when I tried to put "5" in the middle, it became like this. Why?
# Like this
tmp[1][1] = 5
print(tmp)
[[0, 5, 0], [0, 5, 0], [0, 5, 0]]
What that···
It was because I didn't think deeply when I made it.
# Bad example
tmp_ng =[[0] * 3] * 3
print(tmp_ng)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Alright, OK! (* Not OK ...)
# Improvement example
tmp_ok = [[0] * 3 for _ in range(3)]
print(tmp_ok)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
It doesn't change at this point, but ... It will be like this.
tmp_ng[1][1] = 5
print(tmp_ng)
[[0, 5, 0], [0, 5, 0], [0, 5, 0]]
tmp_ok[1][1] = 5
print(tmp_ok)
[[0, 0, 0], [0, 5, 0], [0, 0, 0]]
>>> tmp_ok[0] == tmp_ok[2]
True
>>> tmp_ng[0] == tmp_ng[2]
True
>>> tmp_ok[0] is tmp_ok[2]
False
>>> tmp_ng[0] is tmp_ng[2]
True
In a bad example, the object (?) [0] * 3 created by new (in C #) is set in 3 places. In other words, an array is created in which the variable is defined once and the memory allocated location is referenced three times. Therefore, one type of value appears in three places. However, in the improvement example, [0] * 3 is new (in C #) every time the for _ in range (3) is turned 3 times. Since the memory is secured 3 times, each can have a different value.
I see. .. ..
You can't say that you can write Python unless you can naturally recognize the meaning of each character literal, especially the control command.
Recommended Posts