François Reijers
François Reijers

Reputation: 13

How to iterate over a matrix only taking the diagonal values and change them python without np

I have a "square" Matrix (the number of columns = number of rows):

like:

m = [[10,11,12],
 [13,14,15],
 [16,17,18]]

I need an iteration that takes the values: m[0][0], m[1][1] and m[2][2] and adds 1 to the number so it returns:

m = [[11,11,12],
 [13,15,15],
 [16,17,19]]

Upvotes: 0

Views: 465

Answers (1)

0x263A
0x263A

Reputation: 1859

Since m is a square we can simply iterate across the list and increment the ith element of each list by one:

m = [[10,11,12],
 [13,14,15],
 [16,17,18]]

for i, lst in enumerate(m):
    lst[i] += 1 

print(*m, sep='\n')

Outputs:

[11, 11, 12]
[13, 15, 15]
[16, 17, 19]

Upvotes: 3

Related Questions