0

Why is the matrix filled with namedtuples like this?

Incorrectly inserted indexes

And how to fix it?

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
m, n = 3, 3
matrix = [[None] * n] * m
for i in range(m):
    for j in range(n):
        matrix[i][j] =  Point(i, j)
for row in matrix:
    print(row)

#>>Output
#[Point(x=2, y=0), Point(x=2, y=1), Point(x=2, y=2)]
#[Point(x=2, y=0), Point(x=2, y=1), Point(x=2, y=2)]
#[Point(x=2, y=0), Point(x=2, y=1), Point(x=2, y=2)]

The result should be

#>>Output
#[Point(x=0, y=0), Point(x=0, y=1), Point(x=0, y=2)]
#[Point(x=1, y=0), Point(x=1, y=1), Point(x=1, y=2)]
#[Point(x=2, y=0), Point(x=2, y=1), Point(x=2, y=2)]
Vartan
  • 3
  • 3

2 Answers2

2

Because [] * m is making m copies of the same list (they are referencing the same list). So when you change one of them, it changes all of them. Therefore at the very end, the last row is over-writing whatever values you had filled in the previous ones.

Change your initialization to matrix = [[[None] for i in range(n)] for j in range(m)] and it will work just fine.

Here's another StackOverflow answer demonstrating the side effects of initializing a 2D array this way.

Antimony
  • 2,230
  • 3
  • 28
  • 38
0

I don't know why, but code below works and above not

for k in range(m):
    matrix[k] = [Point(k, i) for i in range(n)]
Serg Anuke
  • 168
  • 2
  • 11