- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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))
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
- Count distinct elements in an array in C++
- Check if all array elements are distinct in Python
- Count subarrays having total distinct elements same as original array in C++
- Product of non-repeating (distinct) elements in an Array in C++
- Absolute distinct count in a sorted array?
- Program to find maximum product of two distinct elements from an array in Python
- Count of subsequences having maximum distinct elements in C++
- Count number of elements in an array with MongoDB?
- Count frequencies of all elements in array in Python
- Absolute distinct count in a sorted array in C++?
- Count and Sum of composite elements in an array in C++
- Python - Count distinct in Pandas Aggregation with Numpy