-1
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]]

vinoth s
  • 29
  • 4
  • 2
    This `a=[[None]*3]` gives you three references to the same list. When you change one you change them all. – Mark May 31 '20 at 05:52
  • 1
    @MarkMeyer I think the problem is the `a=a*3`. The `[None]*3` part should be fine. – gilch May 31 '20 at 06:11
  • Yes @glitch, You are right. Basically its cloning three variable references. if you think of a pointer, its pointing to the same reference of **a**. – Shafay May 31 '20 at 06:17
  • Right @gilch. My mistake. – Mark May 31 '20 at 06:42

2 Answers2

1

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)
Shafay
  • 187
  • 2
  • 7
0

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]]
Leo Arad
  • 4,452
  • 2
  • 6
  • 17