In the previous article we discussed how to to obtain the average/mean of a given list, now we will see how we can write a program to Count Distinct Elements in a List in Python. Suppose we are given a list L=[10,20,10,30,30,20], we see that there some of the elements occur multiple times within the list. We should return a count of each unique element while ignoring repetition, hence it should return a count of 3.
Suppose we are given the list L=[10,10,10], the value returned as output should be 1 and in the case wherein L=10,20,30] it should return 3 as the result. A real-life scenarios where such a program might come in handy is when there is a need to count unique user visits to a site, how many users are logged in to a service or how many users are online at the present.
Program to Count Distinct Elements in a List in Python
Let us discuss a simple method to handle this problem, we initialize our result as ‘1’. We start traversing from the second item and increasing the count by 1 as each element is passed, however while traversing through them we check if we have already seen another element with the same value, if it does we do not increase the count.
def cDistinct(l): res=1 for i in range(1,len(l): if l[i] not in l[0:i]: res=res+1 return res l=10,20,10,30,30,20] print(cDistinct(l))
Th loop performs a slicing operation to inspect the elements of the list, once the program traverses through all the elements we obtain the count of all the distinct elements in the list.
Alternatively we can use set container to count the distinct elements of a given list. Once a given list is contained in a set, the resulting set cannot contain repeated values of existing elements as set can only contain distinct elements. We can then use the built-in len( ) function to return the length of set elements.
def cDistinct(l): s=set(l) return len(s) l=[10,20,10,30,30,20] print(cDistinct(l))
If we go for maximum optimization, even the function statements can be reduced to a single line.
def cDistinct(l): return len(set(l)) l=[10,20,10,30,30,20] print(cDistinct(l))
Thus, we have seen the ways in which we can obtain the count of distinct elements in a list. In the next article we will look at how we can check if a list’s elements are sorted according to order.