itertools.ilen?

Jeremy Fincher fincher.* at osu.edu
Thu Aug 7 09:10:10 CEST 2003


Sometimes I find myself simply wanting the length of an iterator.  For
example, to collect some (somewhat useless ;)) statistics about a program
of mine, I've got code like this:

        objs = gc.get_objects()
        classes = len([obj for obj in objs if inspect.isclass(obj)])
        functions = len([obj for obj in objs if inspect.isroutine(obj)])
        modules = len([obj for obj in objs if inspect.ismodule(obj)])
        dicts = len([obj for obj in objs if type(obj) == types.DictType])
        lists = len([obj for obj in objs if type(obj) == types.ListType])
        tuples = len([obj for obj in objs if type(obj) == types.TupleType])

Now, obviously I can (and will, now that 2.3 is officially released :))
replace the list comprehensions with itertools.ifilter, but I need an
itertools.ilen to find the length of such iterators.

I can imagine such a need arises in more useful situations than this, but
this is the particular case that brought the need to mind.

The Python code is simple, obviously:

def ilen(iterator):
    i = 0
    for _ in iterator:
        i += 1
    return i

But it's a pity to use itertools' super-fast iterators and have to use slow,
raw Python to determine their length :)

Jeremy




More information about the Python-list mailing list