170

I currently have a Python set of n size where n >= 0. Is there a quick 1 or 2 lines Python solution to do it? For example, the set will look like:

fruits = set(['apple', 'orange', 'watermelon', 'grape'])

The goal is to pick 2 random items from the above and it's possible that the above set can contain 0, 1 or more items. The only way I can think of doing the above is to convert the set to a list(mutable) from where I can access 2 random unique index within the length of the set.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Thierry Lam
  • 45,304
  • 42
  • 117
  • 144

1 Answers1

340

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Joel
  • 22,598
  • 6
  • 69
  • 93
John Millikin
  • 197,344
  • 39
  • 212
  • 226
  • 1
    and can be used with `set` as well – SilentGhost Aug 11 '09 at 21:18
  • 4
    Consider using a set in your example. The question explicitely asks for a set (which cannot be passed to `random.choice()` for example) so I'd say it'd improve the answer. – ThiefMaster Aug 23 '12 at 02:19
  • 19
    It's worth noting that internally, this turns the set into a list or tuple (depending on the sizes of the set and the sample) and then runs the sampling procedure. It won't, say, run [reservoir sampling](http://en.wikipedia.org/wiki/Reservoir_sampling) or some other algorithm that works on non-indexable collections. – user2357112 Dec 22 '13 at 10:46
  • Does the set() has any effect here? it should be exactly the same as doing: random.sample([1, 2, 3, 4, 5, 6], 2) – zvisofer Apr 28 '14 at 18:35
  • from the docs: Return a k (2nd argument, k=2 above) length list of *unique* elements. – Charles L. Jul 31 '14 at 00:18
  • What if I wanna get the rest of items after the random choice? – Karyo Oct 29 '14 at 03:57
  • 9
    You should mention if this is a random choice with or without replacement – richnis Jan 09 '15 at 13:04
  • will it work with set of strings? – AbtPst Feb 01 '16 at 21:50
  • @user2357112supportsMonica but on the wikipedia they are using indexes to acces an nth element from the sequence. Reservoir sampling thus needs indexable collection! – Adam Bajger Nov 10 '20 at 20:11
  • @AdamBajger: That's an artifact of the pseudocode notation used. Reservoir sampling does not need an indexable collection. [It's straightforward to implement with just an iterator.](https://ideone.com/FcybvK) – user2357112 Nov 10 '20 at 23:18
  • `X = {1,2,3,4}; random.sample(X, 1)` DeprecationWarning: Sampling from a set deprecated since Python 3.9 and will be removed in a subsequent version. – Ross Bencina Aug 15 '23 at 21:22