Counting number of each item in a list.

bearophileHUGS at bearophileHUGS at
Sun Mar 19 18:22:19 CET 2006

With CPython this is probably the faster version, the version with
list.count() has to be used only if you are sure to always have a short
input list, because it's O(n^2):

str_list = ['StringA', 'StringC', 'StringB',
             'StringA', 'StringC', 'StringD',
             'StringA' ]

str_counts = {}
for s in str_list:
    if s in str_counts:
        str_counts[s] += 1
        str_counts[s] = 1


More information about the Python-list mailing list