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

Chris Barker - NOAA Federal chris.barker at noaa.gov
Wed Apr 13 00:52:31 EDT 2016

I also haven't had a use case for random items  from a set, but have
had a use case for randomly ( not arbitrarily ) choosing from a dict
(see trigrams: http://codekata.com/kata/kata14-tom-swift-under-the-milkwood/)

As dicts and sets share implementation, why not both?

Anyway, the hash table has gaps, but wouldn't it be sufficiently
random to pick a random index, and if it's a gap, pick another one? I
suppose in theory, this could be in infinite process, but in practice,
it would be O(1) with a constant of two or three... Better than
iterating through on average half of the keys.

( how many gaps are there? I have no idea )

I know nothing about the implementation, and have not thought
carefully about the statistics, but it seems do-able. I'll just shut
up if I'm way off base.

BTW, isn't it impossible to randomly select from an infinite iterable anyway?


> On Apr 12, 2016, at 6:43 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Guido van Rossum wrote:
>> The problem with your version is that copying the input is slow if it is large.
> Maybe sets should have a method that returns an indexable
> view? The order could be defined as equivalent to iteration
> order, and it would allow things like random.choice to
> work efficiently on sets.
> --
> Greg
> _______________________________________________
> 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/

More information about the Python-ideas mailing list