Find the number of occurrences in the list

 Let's consider a list 

lis = [1,2,3,1,3,2,1,2,1,1,2,3,4]

find the number of occurrences item in list,  Below are the best ways to find the occurrence of the item in the list

Example 1 with the help of the collections module

from collections import Counter
lis = [1,2,3,1,3,2,1,2,1,1,2,3,4]
count = Counter(lis)
print(dict(count))
Output : {1: 5, 2: 4, 3: 3, 4: 1}

Example 2 . With the help of the count method + dict comprehension


lis = [1,2,3,1,3,2,1,2,1,1,2,3,4]
count = {i : lis.count(i) for i in lis }
print(count)
Output : {1: 5, 2: 4, 3: 3, 4: 1}

Example 3 . It loops and it could be more logical 

lis = [1,2,3,1,3,2,1,2,1,1,2,3,4]
count = {}
for i in lis:
    if i in count:
        count[i] += 1
    else:
        count[i] = 1
print(count)
Output : {1: 5, 2: 4, 3: 3, 4: 1}

Think about the above which one is the best solution in term of Time complexity and comment below 









Comments