Loops are an essential part of any programing language. This will help not only in reducing the rewriting of code but also helps in iterating over the lists, tuple.
Here in this blog, I will be iterating over the nested list in order to find its two diagonals and then performing the arithmetic functions over it.
Note: I have taken the 2-D array having an equal number of rows and columns.
Sample two dimensional list:-
Output:-
0
Here in the above piece of code, at first I ma adding the two different diagonals of the 2-d array and then I am taking the difference of these two.
Explanation:-
1st diagonal : 1 + 5 + 9 = 15
2nd diagonal : 3 + 5 + 7 = 15
difference will be zero(0).
Here in this blog, I will be iterating over the nested list in order to find its two diagonals and then performing the arithmetic functions over it.
Note: I have taken the 2-D array having an equal number of rows and columns.
Sample two dimensional list:-
arr = [[1,2,3], [4,5,6], [7,8,9]] sum2 = 0sum1 = 0for i,j in zip(reversed(range(len(arr))), range(len(arr))): sum1 = sum1 + arr[j][j] sum2 = sum2 + arr[j][i] diff = sum1 - sum2 print(abs(diff))
Output:-
0
Here in the above piece of code, at first I ma adding the two different diagonals of the 2-d array and then I am taking the difference of these two.
Explanation:-
1st diagonal : 1 + 5 + 9 = 15
2nd diagonal : 3 + 5 + 7 = 15
difference will be zero(0).