
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
Count Distinct Elements in an Array in Python
In a list in Python we may have duplicate elements. When we count the length of the list we get the total length including the duplicate elements. But in this article we will see how to get the total count of the distinct elements or unique elements in a list.
Example
In the below example we use the counter() from the collections module. In this module a Counter is a dict subclass for counting hashable objects. Counter is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. So from the original list we create another list made up of only the elements whose key values are present once. This is a distinct list of elements. And then we find the length of this new list.
from collections import Counter list = ['Mon', 'Tue', 'Wed', 'Mon','Tue'] print("Length of original list",len(list)) distinct_list= (Counter(list).keys()) print("List with distinct elements:\n",distinct_list) print("Length of distinct list:",len(distinct_list))
Output
Running the above code gives us the following result −
Length of original list 5 List with distinct elements: dict_keys(['Mon', 'Tue', 'Wed']) Length of distinct list: 3