an element from a set

James Mills prologic at shortcircuit.net.au
Sat May 15 02:40:46 EDT 2010


On Sat, May 15, 2010 at 4:23 PM, Carl Banks <pavlovevidence at gmail.com> wrote:
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list?  I can't think of a way off
> hand.

random.choice(...) requires that the object passed to it supports "sequencing".

This means it must implement: __getitem__ (which a list does).

I don't think there is a way to retrieve a random element from a set without
first turning it into a sequence (list) unless the underlying data of
a set were exposed.

--James



More information about the Python-list mailing list