change every value of a 2d array in python

Question:

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.

Asked By: Edu

||

Answers:

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.

Answered By: Tim Roberts