Last day I was trying for a method to find the count of unique items in a list. I found two solutions. Thought like it is worth to share here.

Method 1:

This method works only with python versions 2.7 and above. The collections library is not available in python versions less than 2.7.

__author__ = 'Amal G Jose'
from collections import Counter
data_list = ['apple', 'apple', 'orange', 'mango', 'apple', 'grapes', 'banana', 'banana']
count = Counter(data_list)
print count.items()
print "Count of apple : ", count['apple']
print "Count of orange : ", count['orange']
print "Count of banana : ", count['banana']
print "Count of grapes : ", count['grapes']
print "Count of mango : ", count['mango']

view raw
ListCountMethod1.py
hosted with ❤ by GitHub

Method 2:

This is a very simple method using python dictionary. This will work in all versions of python.

__author__ = 'Amal G Jose'
count = {}
data_list = ['apple', 'apple', 'orange', 'mango', 'apple', 'grapes', 'banana', 'banana']
for value in data_list:
if value in count.keys():
count[value] += 1
else:
count[value] = 1
print count
print "Count of apple : ", count['apple']
print "Count of orange : ", count['orange']
print "Count of banana : ", count['banana']
print "Count of grapes : ", count['grapes']
print "Count of mango : ", count['mango']

view raw
ListCountMethod2.py
hosted with ❤ by GitHub