Python - List Comprehensions to pull out a diagonal from Matrixes

Introduction

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.

Demo

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 )

Result

The following code scales the column index to fetch M[0][2], M[1][1], etc.:

Demo

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 )

Result

Apply an operation to every item in a matrix, producing results in either a simple vector or a matrix of the same shape:

Demo

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 )

Result

Related Topic