a_list.count(a_callable) ?

Dustan DustanGroups at gmail.com
Thu Jun 14 16:37:59 EDT 2007


On Jun 14, 2:53 pm, Ping <ping.nsr.... at gmail.com> wrote:
> Hi,
>
> I'm wondering if it is useful to extend the count() method of a list
> to accept a callable object?  What it does should be quite intuitive:
> count the number of items that the callable returns True or anything
> logically equivalent (non-empty sequence, non-zero number, etc).
>
> This would return the same result as len(filter(a_callable, a_list)),

map and filter are basically obsolete after the introduction of list
comprehensions; your expression is equivalent to:
len([i for i in a_list if a_callable(i)])

Which can then be converted into a generator expression (round
brackets instead of square brackets) to avoid the intermediate list:
len((i for i in a_list if a_callable(i)))

Or syntactically equivalent (avoiding lispy brackets):
len(i for i in a_list if a_callable(i))

> but without constructing an intermediate list which is thrown away
> after len() is done.
>
> This would also be equivalent to
> n = 0
> for i in a_list:
>     if a_callable(i):  n += 1
> but with much shorter and easier-to-read code.  It would also run
> faster.
>
> This is my first post and please bear with me if I'm not posting it in
> the right way.
>
> Regards,
> Ping





More information about the Python-list mailing list