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’ and list comprehension is used.

Example

Below is a demonstration of the same

my_list = [[45, 67, 85, 42, 11], [78, 99, 10, 13, 0], [91, 23, 23, 64, 23], [91, 11, 22, 14, 35]]

print("The list is :")
print(my_list)

my_result = []

for index, element in enumerate(my_list):
   my_result.append([ele for index_1, ele in enumerate(element) if index_1 != index])

print("The resultant matrix is :")
print(my_result)

Output

The list is :
[[45, 67, 85, 42, 11], [78, 99, 10, 13, 0], [91, 23, 23, 64, 23], [91, 11, 22, 14, 35]]
The resultant matrix is :
[[67, 85, 42, 11], [78, 10, 13, 0], [91, 23, 64, 23], [91, 11, 22, 35]]

Explanation

  • A list of list is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over using ‘enumerate’.

  • The list comprehension is used within the iteration previously.

  • Here, it is checked to see if the element’s index is same as index of enumerated element.

  • If they are not equal, it is appended to the empty list.

  • This is displayed as the output on the console.

Updated on: 16-Sep-2021

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements