[Python-ideas] A function that gives you the number of items in an arbitrary iterable (not len)

Nick Coghlan ncoghlan at gmail.com
Fri Jul 29 02:37:46 CEST 2011


On Fri, Jul 29, 2011 at 9:56 AM, Andrew McNabb <amcnabb at mcnabbs.org> wrote:
> I've done this before:
>
> sum(1 for x in it)
>
> I don't do it frequently enough that a builtin would seem necessary.

Yeah, sum(1 for x in itr) and sum(1 for x in itr if cond(x)) are the
current idiomatic ways to handle the situations mentioned in the OP.

You could suggest itertools.exhaust(itr) to Raymond Hettinger, though.
The sum() idiom works, but isn't particular obvious to readers. OTOH,
it's also pretty trivial to hide the sum() idiom inside a function.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list