I'm still a beginner so if the explanation is wrong or if I should write more, please tell me.
There is a list that contains -
as many as mx to make my.
mx,my = 3,3
l = [list('-'*mx)]*my
print(l)
# [['-','-','-'],['-','-','-'],['-','-','-']]
The result is as expected.
But suppose you want the first of the second list to be +
.
Then that! ??
l[1][0] = '+'
print(l)
# [['-','+','-'],['-','+','-'],['-','+','-']]
The list doesn't meet my expectations. I just wanted to do it on the second list, but it's all over.
If you check all the identification IDs with the id function
print(id(l[0]))
# 40116936
print(id(l[1]))
# 40116936
print(id(l[2]))
# 40116936
All the same ... No matter where you put it, the same ID will be entered because it has the same ID as the others. (The explanation of the reason may not be appropriate)
I could do it by making new ones one by one with the for statement.
mx,my = 3,3
l = [['-' for x in range(mx)] for y in range(mx)]
If you put +
in the first of the second list
l[1][0] = '+'
print(l)
# [['-','-','-'],['-','-','-'],['-','+','-']]
The result was as expected.
the end
Recommended Posts