a_list.count(a_callable) ?

Dustan DustanGroups at gmail.com
Fri Jun 15 11:17:25 EDT 2007


On Jun 15, 9:15 am, Ping <ping.nsr.... 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.

Then wrap it in a function:
def count(a_list, a_function):
   return sum(1 for i in a_list if a_function(i))

And call the function. You can also give it a different name (although
I can't think of a concise name that would express it any better).

> 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.

Indeed, the ambiguity in that situation would be a reason *not* to
introduce such behavior, especially since it would break older
programs that don't recognize that behavior. Just stick with writing
the function, as shown above.




More information about the Python-list mailing list