Check if list contains all unique elements in Python



A list in python can contain elements all of which may or may not be unique. But for a scenario when we need unique elements like marking the attendance for different roll numbers of a class. Below is the approaches with can use.

With Set()

A python set is a collection which is unordered, unindexed and also contains unique elements. So we will compare the length of the set created from the list with the length of the list itself. They will be equal only if there are unique elements in the list.

Example

 Live Demo

# Given List
Alist = ['Mon','Tue','Wed']
print("The given list : ",Alist)

# Compare length for unique elements
if(len(set(Alist)) == len(Alist)):

   print("All elements are unique.")
else:
   print("All elements are not unique.")

Output

Running the above code gives us the following result −

The given list : ['Mon', 'Tue', 'Wed']
All elements are unique.

Running the same program again without having unique elements.

Example

 Live Demo

# Given List
Alist = ['Mon','Tue','Wed','Mon']
print("The given list : ",Alist)

# Compare length for unique elements
if(len(set(Alist)) == len(Alist)):

   print("All elements are unique.")
else:
   print("All elements are not unique.")

Output

Running the above code gives us the following result −

The given list : ['Mon', 'Tue', 'Wed', 'Mon']
All elements are not unique.

With count()

We can also use the in-built count() which will count the frequency of each element in the list. If the count is greater than 1 then we have duplicates in the list.

Example

 Live Demo

# Given List
list1 = ['Mon','Tue','Wed','Mon']
list2 = ['Mon','Tue','Wed']


def dupcheck(x):
   for elem in x:
      if x.count(elem) > 1:
         return True
      return False

if dupcheck(list1):
   print("The given list : ", list1)
   print("There are duplicates.")
else:
   print("The given list : ", list1)
   print("No duplicates.")

if dupcheck(list2):
   print("The given list : ", list2)
   print("There are duplicates.")
else:
   print("The given list : ", list2)
   print("No duplicates.")

Output

Running the above code gives us the following result −

The given list : ['Mon', 'Tue', 'Wed', 'Mon']
There are duplicates.
The given list : ['Mon', 'Tue', 'Wed']
No duplicates.
raja
Published on 09-Sep-2020 12:18:42
Advertisements