Python program to select from a list
Published on Aug. 22, 2023, 12:16 p.m.
To select a random element from a list in Python, you can use the random module along with the choice() function. Here’s an example:
import random
my_list = ['apple', 'banana', 'cherry']
random_element = random.choice(my_list)
print(random_element) # Output: a randomly selected string element from my_list
In this example, we first import the random module. We then define a list my_list containing string elements. We use the choice() function from the random module to select a random element from the list, and store it in random_element. Finally, we print random_element, which contains a randomly selected string element from my_list.
Note that you can modify the my_list variable to contain any kind of elements, including integers and other objects. Also, you can use the randint() function from the random module to select a random integer index from the list, and then use that index to access the corresponding element in the list.