# Python Program to Remove First Diagonal Elements from a Square Matrix

• Last Updated : 24 Jan, 2021

Given a square matrix of N*N dimension, the task is to write a Python program to remove the first diagonal.

Examples:

Input : test_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]

Output : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]

Explanation : Removed 5, 6, 4, 3, 5 from lists, 1st diagonals.

Input : test_list = [[5, 3, 3, 2], [5, 6, 7, 8], [9, 3, 4, 6], [0, 1, 2, 3]]

Output : [[3, 3, 2], [5, 7, 8], [9, 3, 6], [0, 1, 2]]

Explanation : Removed 5, 6, 4, 3 from lists, 1st diagonals.

Method 1 : Using loop and enumerate()

In this we iterate through each row using loop, and compare index of element with row number, if found equal, the element is omitted.

Program:

## Python3

 # initializing listtest_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [    9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]  # printing original listprint("The original list is : " + str(test_list))  res = []for idx, ele in enumerate(test_list):      # removing element whose index is equal to row index    res.append([el for idxx, el in enumerate(ele) if idxx != idx])  # printing resultprint("Filtered Matrix : " + str(res))

Output:

The original list is : [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]

Filtered Matrix : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]

Method 2 : Using list comprehension and enumerate()

In this, we perform task of iteration using list comprehension, providing one liner solution to above method.

Program:

## Python3

 # initializing listtest_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [    9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]  # printing original listprint("The original list is : " + str(test_list))  # list comprehension to perform task as one linerres = [[el for idxx, el in enumerate(ele) if idxx != idx]       for idx, ele in enumerate(test_list)]  # printing resultprint("Filtered Matrix : " + str(res))

Output:

The original list is : [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]

Filtered Matrix : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]

My Personal Notes arrow_drop_up