Python program to remove rows with duplicate element in Matrix


When it is required to remove rows with duplicate element in a matrix, a list comprehension and the ‘set’ operator is used.

Example

Below is a demonstration of the same −

my_list = [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]]

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

my_result = [element for element in my_list if len(set(element)) == len(element)]

print("The result is :")
print(my_result)

Output

The list is :
[[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]]
The result is :
[[17, 46, 47], [28, 91, 19]]

Explanation

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

  • A list comprehension is used to iterate over the elements in the list, and the length of the unique element is compared to the length of every element in the list.

  • If they are equal, it is stored in the list and assigned to a variable.

  • This is displayed as the output on the console.

Updated on: 08-Sep-2021

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements