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

Mike Graham mikegraham at gmail.com
Thu Jul 28 23:56:29 CEST 2011


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



More information about the Python-ideas mailing list