Select Random Element from Set in Python

In this article, we will see how to select a random element from a set in Python.
We have the random module in Python which implements pseudo-random number generators for various distributions including integer, float.
Also, we will see to randomly select multiple choices from a set.

Random number operations in set in Python

random.choice()

This function retrieves a single element from the set.

# program using choice() function

import random
set = (11, 22, 33, 44, 55, 66, 77, 88) 

print("A random number from the set is: " , random.choice(set))

Output:

A random number from the set is: 77

random.choices()

As we know random.choice() is used for selecting single element whereas random.choices()  is used to select multiple elements specified in its argument.  This function takes 2 arguments, set_name  and k(number of random items)

import random

movie_list = ('Godfather', 'Modern Times', 'Casablanca', 'Metropolis', 'Mary Poppins', 'Spartacus')
item = random.choices(movie_list, k=2)

print("Randomly selected items from movie_list are: ", item)

Output:

Randomly selected items from movie_list are:  ['Spartacus', 'Godfather']

 

random.sample()

Likewise, random.sample() can be used instead  random.choices(). Both arguments and output for random.sample() are similar to random.chocies().

import random

movie_list = ('Godfather', 'Modern Times', 'Casablanca', 'Metropolis', 'Mary Poppins', 'Spartacus')
item = random.sample(movie_list, k=2)

print("Randomly selected items from movie_list are: ", item)

Output:

Randomly selected items from movie_list are:  ['Metropolis', 'Casablanca']

randrange()

Furthermore, many times we need an item from a set along with its index position. We can accomplish it by making use of randrange() function. So let us now see how randomly chose an item along with its index number.

from random import randrange

movie_list = ('Godfather', 'Modern Times', 'Casablanca', 'Metropolis', 'Mary Poppins', 'Spartacus')
random_index = randrange(len(movie_list))
movie_item = movie_list[random_index]
print ("Randomly selected item and its index is - ", movie_item, "\nIndex - ", random_index)

Output:

Randomly selected item and its index is -  Casablanca 
Index -  2

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *