[Baypiggies] len(iterable)

Tung Wai Yip tungwaiyip at yahoo.com
Wed Aug 6 22:11:38 CEST 2008

I can think of 2 ways,

>>> it = xrange(10)
>>> len(list(it))

>>> it = xrange(10)
>>> sum(1 for i in it)

Wai Yip

> I have an iterable, and I want to find out how long it is.  I don't
> care if it consumes the iterable.  Furthermore, I know the iterable is
> not infinite.  Consider:
>>>> len((i for i in xrange(10)))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: object of type 'generator' has no len()
> It makes sense that len() not be defined, but I can't seem to find a
> simple count function.  Of course, I can write one, but it seems like
> it should exist in itertools or something.  (By the way, the count
> function in itertools is something completely different.)
> Thanks,
> -jj

More information about the Baypiggies mailing list