[Python-ideas] random.choice on non-sequence
tim.peters at gmail.com
Tue Apr 12 22:07:43 EDT 2016
> 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.
Well, sets and dicts are implemented very similarly in CPython. Note
that a dict view (whether of keys, values or items) doesn't support
indexing! It's unclear how that could be added efficiently, and the
same applies to sets. Iteration works pretty efficiently, because a
hidden "search finger" is maintained internally, skipping over the
gaps in the hash table as needed (so iteration can, internally, make a
number of probes equal to the number of hash slots, and no more than
that) - but that's no help for indexing by a random integer.
I'll just add that I've never had a real need for a random selection
from a set. For all the many set algorithms I've coded, an
"arbitrary" element worked just as well as a "random" element, and
set.pop() works fine for that.
More information about the Python-ideas