Selecting a random element from a group of samples is a deterministic task. A computer program can mimic such a simulation of random choices by using a pseudo-random generator. In this article, we will learn how to select a random element from a set in Python.
What is a set in Python?
A Set is an unordered collection of elements that are iterable, mutable, and has no duplicate elements. The elements within a set can be heterogeneous. Sets utilize a structure known as a hash table to find a given element, making them faster and more efficient in processing than a list. Since sets are unordered, we cannot access items using indexes as we do in lists. The syntax of a set is as follows:
variable_name = {element_one, element_two, element_three}
Where element_one/two/three is any datatype present within Python.
Selecting a random element from a set
Selecting a random element from within several elements could be accomplished by using a pseudo-random generator. For this, the functions in the random library would be used.
Using the choice function
The choice function chooses a random element from a non-empty sequence. The function takes in argument a sequence and returns a random element from it. The following example demonstrates the use of the choice function to select a random element from a predefined set:
Python
import random # A set containing elements of different datatype set = ( 1 , "Hello" , 38 , 44.45 , "Apples" , False ) print ( "An element from the set:" , random.choice( set )) |
Output:
An element from the set: 38
Explanation:
Firstly a set is defined as containing several elements of different data types. Then the choice function is called, and the set is passed as an argument. The function returns a random element from the set.
Using the randrange function
The randrange function chooses a random item from the given range. The function takes in argument a range (or an endpoint) and returns a random item from the range without including the bounds. The following example demonstrates the use of the randrange function to select a random element from a predefined set:
Python3
import random # A set containing elements of different datatype set = ( 1 , "Hello" , 38 , 44.45 , "Apples" , False ) # Passing the length of the set as an argument to the function # This produces a random integer between the index 0 to Len-1 element = random.randrange( 0 , len ( set )) # Obtaining a element from the list based on its index # Where the index is obtained randomly print ( "An element from the set:" , set [element]) |
Output:
An element from the set: 38
Explanation:
The same set as the previous example has been defined at first. Then the function randrange is called, and the length of the set is passed as an argument. The function produces a random integer in the given range which is stored in a variable. In the end, the element associated with that index (denoted by the random integer) inside the set is displayed.