-1

g is a list of list, I use it as a 2d array. But when I assign values to g[i][j], it doesn't work.

Here is my code.

m=3
n=4 
g=[[0]*n]*m
for i in range(m):
    for j in range(n):
        g[i][j]=i
        print(g[i][j])

print(g)

the output is

0
0
0
0
1
1
1
1
2
2
2
2
[[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jian
  • 191
  • 1
  • 9

1 Answers1

2

This

g=[[0]*n]*m

is the problem. Try this instead:

g=[[0]*n for _ in range(m)]

The difference between these two approaches is that, the former is a list of m items, each is the same list of n zeros. But the latter, is a list of m items that each is a different list of n zeros.

adrtam
  • 6,991
  • 2
  • 12
  • 27