Make a Diagonal Matrix

Linear AlgebraEasy+10 XP+10

Make a Diagonal Matrix

A diagonal matrix carries numbers down its main diagonal and zeros everywhere else. Given a list of n values, build the n × n matrix that holds them.

Task: write make_diagonal(values) returning that matrix as a list of rows.

  • values[i] goes at row i, column i. Every other entry is 0.
  • The result is always square: len(values) rows, each len(values) long.
  • Keep the values exactly as given — don't round or convert them. Use plain integer 0 for the empty slots.
  • A single value gives you a 1×1 matrix.

These matrices are worth recognising because multiplying by one is just scaling each coordinate independently — the first axis by the first value, the second by the second, with nothing mixing between them. That's why the identity matrix is diagonal with all ones (scale everything by 1, i.e. change nothing), and why a zero on the diagonal flattens that axis away for good, which is exactly when a matrix stops being invertible.

Examples

values = [1, 2, 3]
returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
values = [0, 5]
returns [[0, 0], [0, 5]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run