a=[[None]*3]
a=a*3
k=0
for i in range(3):
for j in range(3):
a[i][j]=k
print(a)
k=k+1
print(a)
I want the output to be [[0,1,2],[3,4,5],[6,7,8]]. What I am getting is [[6,7,8],[6,7,8],[6,7,8]]
a=[[None]*3]
a=a*3
k=0
for i in range(3):
for j in range(3):
a[i][j]=k
print(a)
k=k+1
print(a)
I want the output to be [[0,1,2],[3,4,5],[6,7,8]]. What I am getting is [[6,7,8],[6,7,8],[6,7,8]]
Mistake is Reference Change of a Variable which impacts every list element. Go with the following approach.
n,m = 3, 3
a = [[0] * m for i in range(n)]
k=0
for i in range(3):
for j in range(3):
a[i][j]=k
k=k+1
print(a)
You need to copy each list from a
because when using multiple it creates a copy of each list that references to the same list so this way you are getting 3 identical lists that only the last iteration value is in it.
a=[[],[],[]]
a=[a[:], a[:], a[:]]
k=0
for i in range(3):
for j in range(3):
a[i][j]=k
k+=1
print(a)
Output
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]