Python – Test if all elements are unique in columns of a Matrix

When it is required to test if all elements are unique in columns of a matrix, a simple iteration and a list comprehension along with the 'set' operator are used.

Below is a demonstration of the same ?

Example

my_matrix = [[11, 24, 84], [24, 55, 11], [7, 11, 9]]

print("The matrix is:")
print(my_matrix)

my_result = True

for index in range(len(my_matrix[0])):
    column = [row[index] for row in my_matrix]
    
    if len(list(set(column))) != len(column):
        my_result = False
        break

if my_result == True:
    print("All columns are unique")
else:
    print("All columns are not unique")

Output

The matrix is:
[[11, 24, 84], [24, 55, 11], [7, 11, 9]]
All columns are unique

How It Works

The algorithm extracts each column from the matrix and converts it to a set. Since sets only contain unique elements, comparing the length of the original column with the set reveals if duplicates exist.

Example with Duplicate Elements

# Matrix with duplicate elements in column 1
matrix_with_duplicates = [[11, 24, 84], [24, 24, 11], [7, 24, 9]]

print("The matrix is:")
print(matrix_with_duplicates)

result = True

for index in range(len(matrix_with_duplicates[0])):
    column = [row[index] for row in matrix_with_duplicates]
    
    if len(set(column)) != len(column):
        result = False
        print(f"Column {index} has duplicates: {column}")
        break

if result:
    print("All columns are unique")
else:
    print("All columns are not unique")
The matrix is:
[[11, 24, 84], [24, 24, 11], [7, 24, 9]]
Column 1 has duplicates: [24, 24, 24]
All columns are not unique

Using a Function Approach

def check_unique_columns(matrix):
    """Check if all columns in matrix have unique elements"""
    for col_index in range(len(matrix[0])):
        column = [row[col_index] for row in matrix]
        if len(set(column)) != len(column):
            return False
    return True

# Test with different matrices
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]

print("Matrix 1:", matrix1)
print("All columns unique:", check_unique_columns(matrix1))

print("\nMatrix 2:", matrix2)
print("All columns unique:", check_unique_columns(matrix2))
Matrix 1: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
All columns unique: True

Matrix 2: [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
All columns unique: False

Conclusion

Testing column uniqueness in a matrix involves extracting each column using list comprehension and comparing the original length with the set length. This approach efficiently identifies duplicate elements within any column of the matrix.

Updated on: 2026-03-26T00:51:39+05:30

550 Views

Advertisements