Selection of a random element from a collection, like a Set, lets you sample unique, unordered elements such as IDs or tags for various types of simulations and A/B testing. Sets provide O(1) membership testing and automatic deduplication by default, which makes it a perfect choice.
Method 1: Using random.choice()
The most efficient approach to select a random element from a Set in Python is to use the random.choice() method.
If you notice the random.choice(list(Set)) method, we converted a set into an indexable sequence like a list? But why? Why can’t we directly apply the random.choice() method on a Set?Because a Set is not an indexable sequence, such as a list or a tuple.
The .choice() method only works on indexable sequences. That is why it is unordered. If you can’t fix the position of the elements in a collection, it is not an indexable sequence.
import random
shares = {'Kaynes', 'V2', 'Meesho', 'ICICIPrudential'}
random_share = random.choice(list(shares))
print(random_share)
# Output: Meesho (Your output may vary)
The choice() method is a suitable approach for choosing a single element.
Empty Set
The input Set should not be empty while executing this method. If it is, it throws the IndexError.
import random
empty_set = {}
random_share = random.choice(list(empty_set))
print(random_share)
# IndexError: list index out of range
The try-catch mechanism can handle any type of potential exceptions, and that is what you should use to wrap your code.
import random
empty_set = {}
try:
random_share = random.choice(list(empty_set))
print(random_share)
except IndexError as e:
print(f"Error with empty set: {e}")
# Error with empty set: list index out of range
It prevents the program from crashing and notifies the engineer what went wrong!
Method 2: Using random.sample() (For multiple elements)
The random.sample() method lets you select multiple or single elements. But mostly, it is better to use it when you want to select multiple unique elements without replacement.
One thing to note is that it is always better to convert to a list (indexable collection) before applying random.sample() method and then convert back to a set.
import random
num_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
multiple_selection_list = random.sample(list(num_set), 4)
multiple_selection_set = set(multiple_selection_list)
print(multiple_selection_set)
# Output: {9, 2, 1, 6} (Your output will vary due to randomness)
The sample() method accepts an indexable collection and the number of unique samples we want to choose. In our code, we need four random elements, so the output set contains four unique elements.
That’s all!


