This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Add length counter for iterables
Type: enhancement Stage: resolved
Components: Demos and Tools Versions: Python 3.8
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: bugale bugale, r.david.murray, steven.daprano
Priority: normal Keywords:

Created on 2017-11-29 23:00 by bugale bugale, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg307271 - (view) Author: bugale bugale (bugale bugale) Date: 2017-11-29 23:00
I have noticed that there is no convenient way in python to get the number of items in a generator.

For example:
  my_iterable = iter(range(1000))
  len(my_iterable) # Would not work

Of course, something like this would ruin the generator, and it will no longer be usable, but in some use cases one would like to know only the count of something.

It is possible to do it today using this line:
  sum(1 for x in my_iterable)

but it seems odd to me that there is no function like:
that does exactly this
msg307274 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-11-29 23:11
Not every trivial one-liner needs to be in the standard library. In this case, there are two easy (and obvious) ways to do it:

sum(1 for x in iterator)


(The first probably saves memory; the second probably is faster.)

Given how rare it is to care ONLY about the length of an iterator, I see no reason why this needs to be in the std lib. If you disagree, please take it to the Python-Ideas mailing list to get community support first before re-opening this ticket.
msg307459 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2017-12-02 21:18
Guido specifically rejected __len__ for iterators when the iteration protocol was designed.  This has become a FREQ in recent times (Frequently Rejected Enhancement Request :)

The rationale, as I understand it, is that an iterator object should always evaluate to True in a boolean context, but I don't know why.  There is also a consistency argument: since not all iterators *can* have a len, then none should, because if some did and some didn't you couldn't use iterators interchangeably in code the way you can now.  In other words, you can't make __len__ part of the iterator protocol, so iterators don't have a __len__.
Date User Action Args
2022-04-11 14:58:55adminsetgithub: 76353
2017-12-02 21:18:24r.david.murraysetnosy: + r.david.murray
messages: + msg307459
2017-11-29 23:11:36steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg307274

resolution: rejected
stage: resolved
2017-11-29 23:00:53bugale bugalecreate