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

Updating 2D array in python

    size = 10
    table = [[0] * size] * size
    for iter in range(size):
        table[iter][iter] = 9

    for iter in range(size):
        print(table[iter])

I am trying to make all daigonal elements to be 9, but instead it is making all the elements as 9.

>Solution :

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

Try using a nested list comprehension to initialize table:

size = 10
table = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size):
    table[i][i] = 9
for row in table:
  print(row)

Output:

[9, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 9, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 9, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 9, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 9, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 9, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 9, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 9]
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