How do I pick 2 random items from a Python set?

PythonRandom

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThierry LamView Question on Stackoverflow
Solution 1 - PythonJohn MillikinView Answer on Stackoverflow