Iterator length
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Thu Jan 18 18:26:03 EST 2007
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
More information about the Python-list
mailing list