selecting a random item from a set

Raymond Hettinger python at rcn.com
Wed Dec 31 15:42:05 EST 2003


[Tim Peters]
> You can do it in O(1) space now at essentially full C speed via, e.g.,
> 
>     i = random.randrange(len(some_set))
>     random_elt = itertools.islice(some_set, i, None).next()
>     some_set.remove(random_elt)

 . . .

> If the sets are small, you're not going to beat random.choice(tuple(s)).  If
> the sets are large, low-level optimization of an approach with the wrong O()
> behavior is just a monumentally bad idea.  If the sets are of middling size,
> get more ambitious <wink>.

The two solutions above are optimal if you only make one random selection.
If you need multiple selections, then try:

    random.sample(tuple(s), k)


Raymond Hettinger




More information about the Python-list mailing list