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

Matrix indexing in Python

I have been trying figure out what this part the code does can anyone explain it me from what i understand the list will be 3,2,1 and then it will print that 3 times but i do not understand what the t[i][i] does in the code the out put is 6 but i do not know how the answer is gotten however if the list were to be printed 4 times of 3 then i have an idea of how the 6 came about

T = [[3-i for i in range (3)] for j in range (3)]
s = 0
for i in range(3):
    s += T[i][i]
print(s)

>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

I just added some print statements to your code, now I think that you will find it clear what is happening:

from pprint import pprint

T = [[3-i for i in range (3)] for j in range (3)]
print("T matrix:")
pprint(T, width=15)
s = 0
for i in range(3):
    s += T[i][i]
    print("diagonal item:", T[i][i], "running sum:", s)
print("final sum:", s)

Remember to add print statements to your code when debugging, or use a debugger tool!

Output:

T matrix:
[[3, 2, 1],
 [3, 2, 1],
 [3, 2, 1]]
diagonal item: 3 running sum: 3
diagonal item: 2 running sum: 5
diagonal item: 1 running sum: 6
final sum: 6
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