A note of what I was addicted to when creating an empty multidimensional array
I wanted to create an empty 2D array in the script, so I created it with the following code.
hoge = [[]] * 5
Then, for some reason, I don't get the results I expected. For example,
>>> hoge = [[]] * 5
>>> for i in range(5):
hoge[i].append(i)
When you check the contents of hoge like
>>> print hoge
[[0],[1],[2],[3],[4]]
I thought it would be
>>> print hoge
[[0,1,2,3,4],[1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]]
It has become like this. After all, the object duplicated with * seems to be only a reference to the original object, like the object created by the assignment with =. After all, to create an empty two-dimensional array,
[[] for i in range(5)]
I wonder if it's best to do it.
Recommended Posts