Python Program to Randomly Select an Element From the List
Imagine you have a big jar full of colorful candies, and you want to pick one randomly without looking. When you close your eyes and pick a candy, you don’t know which color you’ll get. This is called randomness, let’s write a python program for this.
Python Code :
The Below Python program randomly selects an element from a list:
import random # Define a list of items my_list = ["apple", "banana", "orange", "pear", "grape"] # Use the random.choice() method to select a random item from the list random_item = random.choice(my_list) # Print the randomly selected item print(random_item)
In this program, we first import the random module, which provides functions for generating random numbers and values. We then define a list of items called my_list.
To select a random item from the list, we use the random.choice() method, which takes a sequence (such as a list) and returns a randomly selected item from that sequence. We pass our my_list variable as the argument to the random.choice() method to select a random item from the list.
Finally, we print the randomly selected item using the print() function. Each time we run the program, a different item will be randomly selected from the list.