Count distinct elements in an array in Python

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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))

chevron_right




My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.