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

PythonServer Side ProgrammingProgramming

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

Live Demo

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

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

my_result = True

for index in range(len(my_list[0])):

column = [ele[index] for ele in my_list]

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 list is :
[[11, 24, 84], [24, 55, 11], [7, 11, 9]]
All columns are unique

## Explanation

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

• A variable is assigned Boolean value ‘True’.

• The list is iterated over, and list comprehension is used to find index of element.

• If a specific condition is fulfilled, i.e if the length of unique elements in the list is not equal to the length of the elements, the Boolean value is initialized to ‘False’.

• The control breaks out of the loop.

• In the end, depending on the Boolean value, the relevant message is displayed on the console.

Published on 04-Sep-2021 10:45:59