Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count distinct elements in an array in Python

  • Difficulty Level : Medium
  • Last Updated : 22 Jan, 2019

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

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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!