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

Guido van Rossum guido at python.org
Sun Oct 5 02:37:01 CEST 2014


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


More information about the Python-ideas mailing list