Counting number of each item in a list.

Bruno Desthuilliers bdesth.quelquechose at
Sun Mar 19 21:36:57 CET 2006

Kent Johnson a écrit :
> 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))

Of course, my bad :(

> or for Python < 2.4

from sets import Set as set
> 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

once for each *distinct* element or str_list (it iterates over the set 
created from 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.

Yeps. But I would benchmark it before choosing one or the other solution.

More information about the Python-list mailing list