How to Select a Random Element from a Tuple in Python

Selecting a random element consists of retrieving one element from a collection in an unpredictable manner. In Python, this can be done easily using different methods provided by the random module. Below are the three different approaches to select a random element from a tuple.

Select a Random Element from a Tuple in Python

Below are the possible approaches to select a random element from a tuple in Python.

  • Using the random.choice Method
  • Using the random.randint Method
  • Using the random.sample Method

Select a Random Element from a Tuple Using the random.choice Method

In this example, we are using the random.choice method to select a random element from the tuple. The random.choice method directly picks one random element from the given sequence.

Python
import random

gfg_courses = ("DSA", "Python", "Java", "Web Development", "Machine Learning")

random_element = random.choice(gfg_courses)
print("Randomly selected course:", random_element)

Output
Randomly selected course: Python

Select a Random Element from a Tuple Using the random.randint Method

In this example, we are using the random.randint method to generate a random index and then use this index to select an element from the tuple. The random.randint method provides a random integer within the specified range.

Python
import random

gfg_courses = ("DSA", "Python", "Java", "Web Development", "Machine Learning")

random_index = random.randint(0, len(gfg_courses) - 1)
random_element = gfg_courses[random_index]
print("Randomly selected course:", random_element)

Output
Randomly selected course: Python

Select a Random Element from a Tuple Using the random.sample Method

In this example, we are using the random.sample method to select a random element from the tuple. The random.sample method returns a list with the specified number of unique elements, and selecting one element gives us the desired random element.

Python
import random

gfg_courses = ("DSA", "Python", "Java", "Web Development", "Machine Learning")

random_element = random.sample(gfg_courses, 1)[0]
print("Randomly selected course:", random_element)

Output
Randomly selected course: DSA