When I use list_1=[[0]*5]*10
to make a list.One element of python list changes, causes the whole column elements changed.
But when I use list_1=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
to make a list.There is no mistake.Why?
My code:
import random
import csv
rows = 10
cols = 5
list_1 = [[0]*cols]*rows #This is wrong.
#list_1 = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] #This is right.
for i in range(rows)
a=random.randint(1,100)
b=random.randint(1,100)
c=random.randint(1,100)
d=random.randint(1,100)
e=random.randint(1,100)
list_1[i][0] = a
list_1[i][1] = b
list_1[i][2] = c
list_1[i][3] = d
list_1[i][4] = e
print(list_1)
When I use list_1 = [[0]*cols]*rows
,the result is :
[[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0],
[12,25,0,1,0]]
All the rows are same.But when I use list_1=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
The result is right.