Issue
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
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]
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.