
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
# 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
# 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
# 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.