Most Efficient way to calculate Frequency of values in a Python list? Most Efficient way to calculate Frequency of values in a Python list? python python

Most Efficient way to calculate Frequency of values in a Python list?


Python2.7+

>>> from collections import Counter>>> L=['a','b','a','b']>>> print(Counter(L))Counter({'a': 2, 'b': 2})>>> print(Counter(L).items())dict_items([('a', 2), ('b', 2)])

python2.5/2.6

>>> from collections import defaultdict>>> L=['a','b','a','b']>>> d=defaultdict(int)>>> for item in L:>>>     d[item]+=1>>>     >>> print ddefaultdict(<type 'int'>, {'a': 2, 'b': 2})>>> print d.items()[('a', 2), ('b', 2)]