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

Ben Finney ben+python at benfinney.id.au
Tue Apr 12 18:57:47 EDT 2016


Rob Cliffe <rob.cliffe at btinternet.com> writes:

> It surprised me a bit the first time I realised that random.choice did
> not work on a set. (One expects "everything" to "just work" in Python!
> :-) )

I am +1 on the notion that an instance of ‘tuple’, ‘list’, ‘set’, and
even ‘dict’, should each be accepted as input for ‘random.choice’.

> On 2011-06-23, Sven Marnach posted 'A few suggestions for the random
> module' on Python-Ideas, one of which was to allow random.choice to
> work on an arbitrary iterable.

I am −1 on the notion of an arbitrary iterable as ‘random.choice’ input.

Arbitrary iterables may be consumed merely by being iterated. This will
force the caller to make a copy, which may as well be a normal sequence
type, defeating the purpose of accepting that “arbitrary iterable” type.

Arbitrary iterables may never finish iterating. This means the call
to ‘random.choice’ would sometimes never return.

The ‘random.choice’ function should IMO not be responsible for dealing
with those cases.


Instead, a more moderate proposal would be to have ‘random.choice’
accept an arbitrary container.

If the object implements the container protocol (by which I think I mean
that it conforms to ‘collections.abc.Container’), it is safe to iterate
and to treat its items as a collection from which to choose a random
item.


Rob, does that proposal satisfy the requirements that motivated this?

-- 
 \        “Some people, when confronted with a problem, think ‘I know, |
  `\       I'll use regular expressions’. Now they have two problems.” |
_o__)                           —Jamie Zawinski, in alt.religion.emacs |
Ben Finney



More information about the Python-ideas mailing list