0

I have a matrix like:

matrix = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

and I have to assign a value to every element based on the formula (2 ∗ i + 3 ∗ j) mod 6, where i and j are the indexes. I'm using the following code to iterate and assign value:

for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        matrix[i][j] = (((2 * i) + (3 * j)) % 6)

but I have this output:

matrix = [
    [4, 1, 4],
    [4, 1, 4],
    [4, 1, 4]
]

instead of the expected:

matrix = [
    [0, 3, 0],
    [2, 5, 2],
    [4, 1, 4]
]

how can I solve this issue? Also, I can't use NumPy to solve this problem.

Edu
  • 11
  • 5

1 Answers1

0

That is NOT how you created your array! If you did, it would work. What you did instead is

matrix = [[0]*3]*3

That gives you three references to a SINGLE list object, not three separate list objects. Initialize it as

matrix = [[0]*3 for _ in range(3)]

or better yet, use numpy.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • It worked like magic! Felt like you were behind me watching my code LOL. But thanks for the answer, I didn't knew about this object difference. – Edu Aug 02 '22 at 23:29
  • Well, I only recognize it because we've all done the same thing at one time or another. – Tim Roberts Aug 03 '22 at 00:04