a_list.count(a_callable) ?

Antoon Pardon apardon at forel.vub.ac.be
Mon Jun 18 06:44:14 EDT 2007


On 2007-06-15, Ping <ping.nsr.yeh at gmail.com> wrote:
>>
>> sum(1 for i in a_list if a_callable(i))
>>
>> --
>> Carsten Haesehttp://informixdb.sourceforge.net
>
> This works nicely but not very intuitive or readable to me.
>
> First of all, the generator expression makes sense only to
> trained eyes.  Secondly, using sum(1 ...) to mean count()
> isn't very intuitive either.
>
> I would still prefer an expression like a_list.count(a_callable),
> which is short, clean, and easy to understand.   :)   However,
> it does produce ambiguities if a_list is a list of callables.
> Should the count() method match values or check return values
> of a_callable?  There are several possible designs but I'm not
> sure which is better.

If you want to check return values, I would thing your callable argument
should make the call. Something like:

def returns_less_than_three(func):
  return func() < 3


ls.count(returns_less_than_three)


Checking the return values implictly, would make it vey hard if not
impossible to check against the callables themselves if you want to.

-- 
Antoon Pardon



More information about the Python-list mailing list