Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Remove First Diagonal Elements from a Square Matrix
When it is required to remove the first diagonal elements from a square matrix, the enumerate function and list comprehension can be used. The first diagonal (main diagonal) consists of elements where the row index equals the column index.
Understanding the Main Diagonal
In a square matrix, the main diagonal contains elements at positions (0,0), (1,1), (2,2), and so on. These are the elements we need to remove ?
Example
Below is a demonstration of removing diagonal elements using enumerate and list comprehension ?
matrix = [[45, 67, 85, 42, 11],
[78, 99, 10, 13, 0],
[91, 23, 23, 64, 23],
[91, 11, 22, 14, 35]]
print("The original matrix is:")
print(matrix)
result = []
for row_index, row in enumerate(matrix):
result.append([element for col_index, element in enumerate(row) if col_index != row_index])
print("The matrix after removing diagonal elements:")
print(result)
The original matrix is: [[45, 67, 85, 42, 11], [78, 99, 10, 13, 0], [91, 23, 23, 64, 23], [91, 11, 22, 14, 35]] The matrix after removing diagonal elements: [[67, 85, 42, 11], [78, 10, 13, 0], [91, 23, 64, 23], [91, 11, 22, 35]]
How It Works
The
enumeratefunction provides both the index and value for each rowFor each row, list comprehension filters out elements where column index equals row index
The condition
col_index != row_indexexcludes diagonal elementsEach filtered row is appended to the result matrix
Alternative Using NumPy
For larger matrices, NumPy provides a more efficient approach ?
import numpy as np
matrix = np.array([[45, 67, 85, 42],
[78, 99, 10, 13],
[91, 23, 23, 64],
[91, 11, 22, 14]])
print("Original matrix:")
print(matrix)
# Create a mask to exclude diagonal elements
mask = ~np.eye(matrix.shape[0], dtype=bool)
result = matrix[mask].reshape(matrix.shape[0], matrix.shape[1] - 1)
print("Matrix after removing diagonal:")
print(result)
Original matrix: [[45 67 85 42] [78 99 10 13] [91 23 23 64] [91 11 22 14]] Matrix after removing diagonal: [[67 85 42] [78 10 13] [91 23 64] [91 11 22]]
Conclusion
Use enumerate with list comprehension for simple diagonal removal. For larger matrices, NumPy provides more efficient operations with boolean masking.
