Iterator length

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Jan 19 15:29:38 EST 2007


Steven D'Aprano:
> since g is not an arbitrary iterator, one can easily do this:
> print [(h,len(list(g))) for h,g in groupby(s)]
> No need for a special function.

If you look at my first post you can see that I have shown that
solution too, but it creates a list that may be long, that may use a
lot of of memory, and then throws it away each time. I think that's a
bad solution. It goes against the phylosophy of iterators too, they are
things created to avoid managing true lists of items too.


> If you, the iterator
> creator, know enough about the iterator to be sure it has a predictable
> length, you know how to calculate it.

I don't agree, sometimes I know I have a finite iterator, but I may
ignore how many elements it gives (and sometimes they may be a lot).
See the simple example with the groupby.

Bye,
bearophile




More information about the Python-list mailing list