Often I need to tell the len of an iterator, this is a stupid example:

>>> l = (i for i in xrange(100) if i&1)

len isn't able to tell it:

>>> len(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()

This is a bad solution, it may need too much memory, etc:

>>> len(list(l))

This is a simple solution in a modern Python:

>>> sum(1 for _ in l)
50

This is a faster solution (and Psyco helps even more):

def leniter(iterator):
    """leniter(iterator): return the length of an iterator,
    consuming it."""
    if hasattr(iterator, "__len__"):
        return len(iterator)
    nelements = 0
    for _ in iterator:
        nelements += 1
    return nelements

Is it a good idea to extend the functionalities of the built-in len
function to cover such situation too?

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to