itertools.ilen?
Raymond Hettinger
vze4rx4y at verizon.net
Thu Aug 7 09:19:40 EDT 2003
"Jeremy Fincher"
> 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 :)
For your application, it is not hard to build a itertools version:
>>> import itertools
>>> def countif(predicate, seqn):
... return sum(itertools.imap(predicate, seqn))
>>> def isEven(x):
... return x&1 == 0
>>> countif(isEven, xrange(1000000))
500000
>>> def isTuple(x):
... return type(x) == types.TupleType
>>> tuples = countif(isTuple, objs)
Raymond Hettinger
More information about the Python-list
mailing list