Get diagonal without using numpy?

For diagonal:

[m[i][i] for i in xrange(0, len(m))]

For counter-diagonal:

[m[i][~i] for i in xrange(0, len(m))]


To get the leading diagonal you could do

diag = [ mat[i][i] for i in range(len(mat)) ]

or even

diag = [ row[i] for i,row in enumerate(mat) ]

And play similar games for other diagonals. For example, for the counter-diagonal (top-right to bottom-left) you would do something like:

diag = [ row[-i-1] for i,row in enumerate(mat) ]

For other minor diagonals you would have to use if conditionals in the list comprehension, e.g.:

diag = [ row[i+offset] for i,row in enumerate(mat) if 0 <= i+offset < len(row)]

Tags:

Python

Matrix