Given positions, we can pull out a diagonal.
The following expressions uses range to generate the list of offsets and then indexes with the row and column the same, picking out M[0][0], then M[1][1], and so on.
M = [[1, 2, 3], [4, 5, 6], # w w w . j a v a 2 s .c o m [7, 8, 9]] d=[M[i][i] for i in range(len(M))] # Diagonals print( d )
The following code scales the column index to fetch M[0][2], M[1][1], etc.:
M = [[1, 2, 3], [4, 5, 6], # from w w w. ja v a 2 s .c o m [7, 8, 9]] d=[M[i][len(M)-1-i] for i in range(len(M))] print( d )
Apply an operation to every item in a matrix, producing results in either a simple vector or a matrix of the same shape:
M = [[1, 2, 3], [4, 5, 6], # from w ww . j a v a2s . c o m [7, 8, 9]] d= [col + 10 for row in M for col in row] # Assign to M to retain new value print( d ) d= [[col + 10 for col in row] for row in M] print( d )