[Baypiggies] len(iterable)
Shannon -jj Behrens
jjinux at gmail.com
Wed Aug 6 22:35:58 CEST 2008
On Wed, Aug 6, 2008 at 1:34 PM, Shannon -jj Behrens <jjinux at gmail.com> wrote:
> 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.
By the way, my rather boring solution was:
def iter_len(iter):
"""Return the length of the given iterator.
len(iter) doesn't work in cases such as::
len((i for i in xrange(10)))
I can't find anything for this in the standard library.
"""
count = 0
for i in iter:
count += 1
return count
def test_iter_len():
assert_equal(iter_len(xrange(5)), 5)
Gees, I'm so boring sometimes!
-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