[Tutor] How many times X is in a list?

Kent Johnson kent37 at tds.net
Wed Dec 20 19:45:20 CET 2006

Luke Paireepinart wrote:
>> Yes, count() is looking for exact matches. You can make a new list with 
>> just the circulation names and take the length of that; something like this:
>> len([name for name in built_Objects if name.startswith('Circulation')])
>> or perhaps slightly more efficient (Python 2.5):
>> sum(1 for name in built_Objects if name.startswith('Circulation'))
> I thought sum only worked on lists.

According to the docs sum() works on sequences, but in fact it seems to 
work on any iterable (a weaker condition than sequence). For example you 
can sum a dict which is not a sequence:
In [4]: d=dict.fromkeys(range(10))
In [6]: sum(d)
Out[6]: 45

> Is that supposed to be a list comprehension inside of sum or am I wrong?

No, it is a generator comprehension which is like a list comp except it 
uses () instead of [] and it creates an iterator rather than a list.

The reason I postulate that using sum() *might* be more efficient is 
because it doesn't have to create the intermediate list. Of course for 
any reasonable size list it won't make a noticable difference anyway...


More information about the Tutor mailing list