How can I randomly select an item from a list?
You can use the random
module's choice
function to select a random element from a list. Here's an example:
import random
my_list = [1, 2, 3, 4, 5]
random_item = random.choice(my_list)
print(random_item)
This will print out a random element from my_list
.
You can also use the random.sample
function to choose a random subset of elements from the list without replacement (i.e., each element will only be chosen once). For example:
import random
my_list = [1, 2, 3, 4, 5]
random_subset = random.sample(my_list, 3)
print(random_subset)
This will print out a list containing three random elements from my_list
.