B
bearophileHUGS
Often I need to tell the len of an iterator, this is a stupid example:
len isn't able to tell it:
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:
This is a simple solution in a modern Python:
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
len isn't able to tell it:
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:
This is a simple solution in a modern Python:
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