Counting number of each item in a list.

Kent Johnson kent at kentsjohnson.com
Sun Mar 19 09:18:45 EST 2006


sophie_newbie wrote:
> Hey Bruno,
> 
> I got an invalid syntax error when i tried using your "str_counts =
> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
> there is a missing bracket or comma? Or maybe I need to import
> something.

It should be
str_counts = dict((s, str_list.count(s)) for s in set(str_list))

or for Python < 2.4
str_counts = dict([(s, str_list.count(s)) for s in set(str_list)])

Note that this solution iterates str_list once for each element of 
str_list - the call to count traverses the entire list to create the 
count. I expect Paul Rubin's solution will be dramatically faster for 
large lists as it only iterates str_list once.

Kent



More information about the Python-list mailing list