Skip to content
Related Articles

Related Articles

Count distinct elements in an array in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 22 Jan, 2019

Given an unsorted array, count all distinct elements in it.

Examples:

Input : arr[] = {10, 20, 20, 10, 30, 10} 
Output : 3

Input : arr[] = {10, 20, 20, 10, 20}
Output : 2

We have existing solution for this article. We can solve this problem in Python3 using Counter method.




from collections import Counter
  
def countDistinct(arr):
  
    # counter method gives dictionary of elements in list
    # with their corresponding frequency.
    # using keys() method of dictionary data structure
    # we can count distinct values in array
    return len(Counter(arr).keys())    
  
if __name__=="__main__":
    arr = [10, 20, 20, 10, 30, 10]
    print (countDistinct(arr))


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!