Input numbers in nested list and find the sum of each row, column, right and left diagonal in Python

Lists - Question 12

In this question, we will see how to input numbers in a 3X3 integer matrix (nested list) and find the sum of each row, each column, right diagonal and left diagonal separately in Python programming. To know more about lists click on the lists lesson.

Q12) Write a program in Python to input numbers in a 3X3 integer matrix (nested list) and find the sum of each row, each column, right diagonal and left diagonal separately. Right Diagonal = \ and Left Diagonal = /.

Program

``````a=[[],[],[]]
r=0;c=0;rs=0;cs=0;rd=0;ld=0

print('Enter 9 numbers')
for r in range(3):
for c in range(3):
a[r].append(int(input()))

for r in range(3):
rs=0
cs=0
rd=rd+a[r][r]
ld=ld+a[r][2-r]
for c in range(3):
print(a[r][c],end=' ')
rs=rs+a[r][c];		# row sum
cs=cs+a[c][r];		# column sum
print('  Row Sum = %d  Column Sum = %d' %(rs,cs))

print('Right Diagonal Sum =',rd)
print('Left Diagonal Sum =',ld)``````

Output

```Enter 9 numbers
18
12
72
10
15
45
38
5
64
18 12 72   Row Sum = 102  Column Sum = 66
10 15 45   Row Sum = 70  Column Sum = 32
38 5 64   Row Sum = 107  Column Sum = 181
Right Diagonal Sum = 97
Left Diagonal Sum = 125```