[Baypiggies] len(iterable)
Shannon -jj Behrens
jjinux at gmail.com
Wed Aug 6 22:34:07 CEST 2008
On Wed, Aug 6, 2008 at 1:11 PM, Tung Wai Yip <tungwaiyip at yahoo.com> wrote:
> I can think of 2 ways,
>
>>>> it = xrange(10)
>>>> len(list(it))
> 10
>
>>>> it = xrange(10)
>>>> sum(1 for i in it)
> 10
>
> 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
I can't do len(list(iter)) because I don't have enough RAM ;) Guido
and Wai Yip's idea was the most elegant. It seems strange that this
isn't in the standard library.
-jj
--
Lisp programmers know the value of everything, but the cost of nothing...
On my Lisp, '() costs 4 bytes.
http://jjinux.blogspot.com/
More information about the Baypiggies
mailing list