
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Count distinct elements in an array in C++
- Sum of distinct elements of an array in JavaScript
- Count subarrays having total distinct elements same as original array in C++
- Check if all array elements are distinct in Python
- Program to find maximum product of two distinct elements from an array in Python
- Product of non-repeating (distinct) elements in an Array in C++
- Absolute distinct count in a sorted array?
- Sum of distinct elements of an array - JavaScript
- Count of subsequences having maximum distinct elements in C++
- Count number of elements in an array with MongoDB?
- Absolute distinct count in a sorted array in C++?
- Upper or lower elements count in an array in JavaScript
- Count frequencies of all elements in array in Python\n
- Count and Sum of composite elements in an array in C++
- Python - Count distinct in Pandas Aggregation with Numpy
