Python – Check Similar elements in Matrix rows

When working with matrices, you might need to identify rows that appear multiple times. Python provides an efficient solution using the Counter class from the collections module to count the frequency of identical rows.

Finding Similar Elements in Matrix Rows

The approach involves converting matrix rows to tuples (since lists aren't hashable) and using Counter to track row frequencies ?

from collections import Counter

def find_duplicate_rows(matrix):
    # Convert rows to tuples for hashing
    matrix_tuples = map(tuple, matrix)
    
    # Count frequency of each row
    freq_dict = Counter(matrix_tuples)
    
    # Display rows that appear more than once
    for (row, freq) in freq_dict.items():
        if freq > 1:
            print(f"Row {row} appears {freq} times")

# Example matrix with duplicate rows
matrix = [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0],
          [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]]

print("The matrix is:")
for row in matrix:
    print(row)

print("\nDuplicate rows found:")
find_duplicate_rows(matrix)
The matrix is:
[1, 1, 0, 1, 0, 1]
[0, 0, 1, 0, 0, 1]
[1, 0, 1, 1, 0, 0]
[1, 1, 0, 1, 0, 1]
[0, 0, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 1]

Duplicate rows found:
Row (1, 1, 0, 1, 0, 1) appears 2 times
Row (0, 0, 1, 0, 0, 1) appears 3 times

Alternative Approach - Return Similar Rows

You can also return the duplicate rows instead of printing them ?

from collections import Counter

def get_similar_rows(matrix):
    # Convert to tuples and count frequencies
    freq_dict = Counter(map(tuple, matrix))
    
    # Return only rows that appear more than once
    return [row for row, freq in freq_dict.items() if freq > 1]

matrix = [[1, 2, 3], [4, 5, 6], [1, 2, 3], [7, 8, 9], [4, 5, 6]]
similar_rows = get_similar_rows(matrix)

print("Matrix:", matrix)
print("Similar rows:", similar_rows)
Matrix: [[1, 2, 3], [4, 5, 6], [1, 2, 3], [7, 8, 9], [4, 5, 6]]
Similar rows: [(1, 2, 3), (4, 5, 6)]

How It Works

  • The map(tuple, matrix) converts each list row to a tuple, making them hashable for Counter

  • Counter creates a dictionary with row tuples as keys and their frequencies as values

  • Rows with frequency > 1 are identified as duplicates

  • The function iterates through the frequency dictionary to find and display similar rows

Conclusion

Using Counter with tuple conversion provides an efficient way to identify duplicate rows in a matrix. This approach is particularly useful for data analysis and matrix processing tasks where row similarity matters.

Updated on: 2026-03-26T02:24:56+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements