[Python-ideas] Make len() usable on a generator
Chris Angelico
rosuav at gmail.com
Fri Oct 10 20:10:52 CEST 2014
On Sat, Oct 11, 2014 at 5:06 AM, <random832 at fastmail.us> wrote:
> On Fri, Oct 10, 2014, at 11:09, Adam Jorgensen wrote:
>> I don't think it makes much sense for len() to work on generators and the
>> fact that sum() works isn't a good argument.
>>
>> Summing the contents of a generator can make sense whereas attempting to
>> obtain the length of something which specifically does not define a
>> length
>> seems a little nonsensical to me...
>
> Why doesn't it define a length? No, hear me out. Is there any reason
> that, for example, generator expressions on lists or ranges shouldn't be
> read-only views instead of generators?
For a start, you'd have to preclude anything with an 'if' in it.
What's the length of this generator?
gen = (sin(x*.0314159) for x in range(100) if f(x))
Without actually exhausting the iterator, there's no way to predict
how many values it'll produce. The only way to do it would be to
restrict this to generators that basically map a function/expression
over an iterable of known length.
ChrisA
More information about the Python-ideas
mailing list