[Python-ideas] __len__() for map()

David Mertz mertz at gnosis.cx
Thu Nov 29 11:39:56 EST 2018


On Thu, Nov 29, 2018 at 2:29 AM Adrien Ricocotam <ricocotam at gmail.com>
wrote:

> Some suggested above to change the definition of len in the long term.
> Then I think it could be interesting to define len such as :
>
> - If has a finite length : return that length (the way it works now)
> - If has a  length that is infinity : return infinity
> - If has no length : return None
>

Do you anticipate that the `len()` function will be able to solve the
Halting Problem?

It is simply not possible to know whether a given iterator will produce
finitely many or infinitely many elements.  Even those that will produce
finitely many do not, in general, have a knowable length without running
them until exhaustion.

Here's a trivial example:

>>> def seq():
...     while random() > 0.1:
...         yield 1
>>> len(seq())
# What answer do you want here?

Here's a slightly less trivial one:

In [1]: from itertools import count
In [2]: def mandelbrot(z):
   ...:     "Yield each value until escape iteration"
   ...:     c = z
   ...:     for n in count():
   ...:         if abs(z) > 2:
   ...:             return n
   ...:         yield z
   ...:         z = z*z + c

What should len(mandelbrot(my_complex_number)) be? Hint, depending on the
complex number chosen, it might be any Natural Number (or it might not
terminate).


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181129/8a86bfcb/attachment.html>


More information about the Python-ideas mailing list