A function that gives you the number of items in an arbitrary iterable (not len)

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 Here are some situations where such a function could come in handy: 1. I want to know how many conditions satisfy a condition. I can currently determine this with code like sum(itertools.imap(cond, it)) or one of several other options. Oftentimes these take longer to read than they should. 2. I simply want to evaluate all the items in a lazy iterable. The nicest way to do this is to the effect of "for item in it: pass", though I have seen creative solutions like collections.deque(iterator, 0) (to try to speed up the loop). 3. You simply want to know the length of a non-sequence iterable. One current way to do this is sum(1 for item in it) (although I think I've seen "for count, _ in enumerate(it): pass;; count += 1"). I think the introduction of a function that works like this might make Python easier to read occasionally. I've seen these all pop up, but only occasionally. None are hard to perform as is, but each can feel a little messy. Does anyone have any input? Mike

On Thu, Jul 28, 2011 at 05:56:29PM -0400, Mike Graham 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. -- Andrew McNabb http://www.mcnabbs.org/andrew/ PGP Fingerprint: 8A17 B57C 6879 1863 DE55 8012 AB4D 6098 8826 6868

On Fri, Jul 29, 2011 at 9:56 AM, Andrew McNabb <amcnabb@mcnabbs.org> wrote:
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@gmail.com | Brisbane, Australia

On Thu, Jul 28, 2011 at 05:56:29PM -0400, Mike Graham 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. -- Andrew McNabb http://www.mcnabbs.org/andrew/ PGP Fingerprint: 8A17 B57C 6879 1863 DE55 8012 AB4D 6098 8826 6868

On Fri, Jul 29, 2011 at 9:56 AM, Andrew McNabb <amcnabb@mcnabbs.org> wrote:
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@gmail.com | Brisbane, Australia
participants (3)
-
Andrew McNabb
-
Mike Graham
-
Nick Coghlan