Working with matrices is a common task in programming, especially when dealing with mathematical or machine-learning problems. In this tutorial, we will learn how to extract the diagonal elements of a matrix using Python.

This can be useful when you want to find the trace of a matrix, which is the sum of the diagonal elements, or when you simply need the diagonal elements of a matrix for further processing.

To accomplish this, we will use Python’s built-in support for **lists** and **slicing**, as well as the popular numerical libraries **numpy** and **pandas**.

### Step 1: Creating a Matrix Using Lists

In Python, we can represent a matrix using a list of lists, where each inner list represents a row of the matrix. Here’s a 3×3 matrix example:

1 2 3 4 5 |
matrix = [ [10, 20, 30], [40, 50, 60], [70, 80, 90], ] |

### Step 2: Extracting the Diagonal Elements

We can extract the diagonal elements of a matrix using simple **list comprehension** and slicing. The diagonal elements are those where the row and column number are the same, i.e., the indices are equal. For a 3×3 matrix, this would be the elements at positions (0,0), (1,1), and (2,2).

To achieve this, you can use the following code:

1 |
diagonal = [matrix[i][i] for i in range(len(matrix))] |

In this code, we use the `range`

function to iterate through the row numbers and indexes, and slice the diagonal elements using the same index for both row and column of the matrix.

Running this code on our example matrix would result in the following diagonal elements:

[10, 50, 90]

### Step 3: Using Numpy to Get the Diagonal Elements

Another common way to work with matrices in Python is by using the **numpy** library. If you don’t have numpy installed, you can install it using pip:

pip install numpy

Now, let’s convert our list-based matrix to a numpy array and extract the diagonal elements using the `numpy.diagonal()`

function:

1 2 3 4 |
import numpy as np numpy_matrix = np.array(matrix) diagonal_numpy = numpy_matrix.diagonal() |

Executing this code will give us a numpy array containing the diagonal elements:

array([10, 50, 90])

### Step 4: Getting the Diagonal Elements Using Pandas

Lastly, let’s extract the diagonal elements using the **pandas** library. This library provides a DataFrame data structure which can be used to represent a matrix.

To get started with pandas, install it using pip if you don’t have it yet:

pip install pandas

Now, let’s create a pandas DataFrame from our list-based matrix and extract the diagonal elements using the `pandas.DataFrame.iloc[]`

indexer:

1 2 3 4 |
import pandas as pd pandas_matrix = pd.DataFrame(matrix) diagonal_pandas = [pandas_matrix.iloc[i, i] for i in range(len(pandas_matrix))] |

This will give us a list containing the diagonal elements:

[10, 50, 90]

## Full Code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import numpy as np import pandas as pd matrix = [ [10, 20, 30], [40, 50, 60], [70, 80, 90], ] # Extract diagonal using list comprehension diagonal = [matrix[i][i] for i in range(len(matrix))] # Extract diagonal using numpy numpy_matrix = np.array(matrix) diagonal_numpy = numpy_matrix.diagonal() # Extract diagonal using pandas pandas_matrix = pd.DataFrame(matrix) diagonal_pandas = [pandas_matrix.iloc[i, i] for i in range(len(pandas_matrix))] print(diagonal_pandas) |

## Conclusion

In this tutorial, we discussed how to extract diagonal elements from a matrix using Python lists, numpy, and pandas. You can choose the method that best fits the data structure and libraries you are already using in your project. Each of these approaches provides a simple and efficient way to extract diagonal elements from a matrix in Python.