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
raja
Published on 07-Aug-2019 11:45:17
Advertisements