Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Matrix Diagonals

Hard · 75 XP

For the 3×3 matrix in the starter, print the sum of the main diagonal, then the sum of the anti-diagonal.

Target output
22
18
Blank · autosaved
PYmatrix-diagonal.py
Run your code to check it…
Guide

How to approach Matrix Diagonals

A matrix in Python is a list of rows, so matrix[row][col] reaches any cell. The main diagonal is every cell where the row and column are the same: matrix[i][i].

The anti-diagonal runs from top-right to bottom-left. As the row goes up from 0, the column comes down from the last index, so the cell is matrix[i][n - 1 - i] for an n × n matrix. Sum each with a generator over range(n).

Worked through on this data

  1. Main diagonal: matrix[0][0] = 5, matrix[1][1] = 8, matrix[2][2] = 9. 5 + 8 + 9 = 22.
  2. Anti-diagonal: matrix[0][2] = 3, matrix[1][1] = 8, matrix[2][0] = 7. 3 + 8 + 7 = 18.
  3. Two prints give 22 and 18. In an odd-sized matrix both diagonals share the centre cell, here the 8.

Common mistakes

  • Writing matrix[i][n - i]: on the first row that is index 3, past the end, and raises an IndexError.
  • Hard-coding 3 instead of len(matrix), so the code breaks on any other size.
  • Adding both diagonals into one total and counting the centre cell twice when the task asks for a combined sum.

Time and space

Each diagonal visits n cells: O(n) time and O(1) extra space, even though the matrix holds n² values.

Where this shows up

Grid indexing shows up in image processing, game boards (checking a tic-tac-toe win is this exact problem) and the trace of a matrix in linear algebra.

Take it further

Write has_winner(board) for a 3 × 3 tic-tac-toe board that checks every row, column and both diagonals.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path