[Python-ideas] Make len() usable on a generator

Thomas t.chaumeny at gmail.com
Sat Oct 11 00:15:55 CEST 2014


Well, I'm already convinced actually :)

The thing is I brought that question based on the fact that "sum(1 for
...)" was slower then "len([foo for ...])" and I thought it was a shame
there were no builtin way to count quickly an iterable.

I realized afterwards that this fact is no longer true, as "sum(1 for ...)"
has become faster with some recent Python version (it looks like it will
not use Python objects addition if all the operands are numbers).

On Fri, Oct 10, 2014 at 5:09 PM, Adam Jorgensen <adam.jorgensen.za at gmail.com
> 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...
>
> On 5 October 2014 02:37, Guido van Rossum <guido at python.org> wrote:
>
>> Support for len() on iterators isn't going to happen.
>>
>> The "gut feeling" reason is that len() shouldn't "consume" anything. It
>> would lure people into thinking they can first call len() on the iterator
>> and then iterate over it -- while, if it is an actual iterator (like an I/O
>> stream), after calling len(), everything is consumed.
>>
>> Yes, it's possible that you only want to count the number of lines, but
>> that's unusual, and the idiom for that is readily available (e.g. sum(1 for
>> ...)). If the idiom occurs frequently in your code you can define a helper
>> function count(). The speed benefit of doing the loop in C would be minimal
>> in most cases.
>>
>> --
>> --Guido van Rossum (python.org/~guido)
>>
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> https://mail.python.org/mailman/listinfo/python-ideas
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141011/a6dd569b/attachment.html>


More information about the Python-ideas mailing list