Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change every value of a 2d array in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading