[Python-ideas] random.choice on non-sequence

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Apr 13 17:47:37 EDT 2016

Chris Angelico wrote:
> On Wed, Apr 13, 2016 at 8:36 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>>On 4/13/2016 12:52 AM, Chris Barker - NOAA Federal wrote:
>>>BTW, isn't it impossible to randomly select from an infinite iterable
>>With equal probability, yes, impossible.
> def choice(it):
>     it = iter(it)
>     value = next(it)
>     try:
>         while random.randrange(2):
>             value = next(it)
>     except StopIteration: pass
>     return value

I think Terry meant that you can't pick just one item that's
equally likely to be any of the infinitely many items returned
by the iterator.

You can prove that by considering that the probability of
a given item being returned would have to be 1/infinity,
which is zero -- so you can't return anything!


More information about the Python-ideas mailing list