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

Andrew McNabb amcnabb at mcnabbs.org
Fri Jul 29 01:56:31 CEST 2011


On Thu, Jul 28, 2011 at 05:56:29PM -0400, Mike Graham wrote:
> There are a couple patterns, some uglier than others, which I have
> seen occasionally pop up which could be solved by a new builtin or
> stdlib that works like
> 
> def exhaust(it):
>     count = 0
>     for item in it:
>         count += 1
>     return count

I've done this before:

sum(1 for x in it)

I don't do it frequently enough that a builtin would seem necessary.

--
Andrew McNabb
http://www.mcnabbs.org/andrew/
PGP Fingerprint: 8A17 B57C 6879 1863 DE55  8012 AB4D 6098 8826 6868



More information about the Python-ideas mailing list