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

Adam Jorgensen adam.jorgensen.za at gmail.com
Fri Oct 10 17:09:42 CEST 2014


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/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141010/c9c13c00/attachment.html>


More information about the Python-ideas mailing list