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 rows with duplicate element in Matrix
When it is required to remove rows with duplicate elements in a matrix, a list comprehension and the set operator is used to filter out rows containing duplicate values.
Understanding the Problem
A matrix (list of lists) may contain rows where elements are repeated. We need to identify and remove such rows, keeping only those with unique elements ?
# Example matrix with some rows having duplicate elements
matrix = [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]]
print("Original matrix:")
for i, row in enumerate(matrix):
print(f"Row {i}: {row}")
Original matrix: Row 0: [34, 23, 34] Row 1: [17, 46, 47] Row 2: [22, 14, 22] Row 3: [28, 91, 19]
Method 1: Using List Comprehension with set()
We can use a list comprehension that compares the length of a set (unique elements) with the original row length ?
matrix = [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]]
print("The original matrix is:")
print(matrix)
# Remove rows with duplicate elements
filtered_matrix = [row for row in matrix if len(set(row)) == len(row)]
print("The matrix after removing rows with duplicates:")
print(filtered_matrix)
The original matrix is: [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]] The matrix after removing rows with duplicates: [[17, 46, 47], [28, 91, 19]]
Method 2: Using Filter Function
Alternatively, we can use the filter() function with a lambda expression ?
matrix = [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]]
print("Original matrix:")
print(matrix)
# Using filter with lambda
filtered_matrix = list(filter(lambda row: len(set(row)) == len(row), matrix))
print("Filtered matrix:")
print(filtered_matrix)
Original matrix: [[34, 23, 34], [17, 46, 47], [22, 14, 22], [28, 91, 19]] Filtered matrix: [[17, 46, 47], [28, 91, 19]]
How It Works
The solution works by comparing two lengths:
len(set(row))− Length of unique elements in the rowlen(row)− Total length of the rowIf both lengths are equal, the row has no duplicates
If lengths differ, the row contains duplicate elements and is excluded
Example with Different Data Types
This method works with different data types as well ?
mixed_matrix = [['a', 'b', 'a'], [1, 2, 3], ['x', 'y', 'z'], [5, 5, 6]]
print("Mixed data type matrix:")
print(mixed_matrix)
result = [row for row in mixed_matrix if len(set(row)) == len(row)]
print("Rows without duplicates:")
print(result)
Mixed data type matrix: [['a', 'b', 'a'], [1, 2, 3], ['x', 'y', 'z'], [5, 5, 6]] Rows without duplicates: [[1, 2, 3], ['x', 'y', 'z']]
Conclusion
Use list comprehension with set() to efficiently remove matrix rows containing duplicate elements. The len(set(row)) == len(row) condition identifies rows with unique elements only.
