random choices in loop in python

To randomly choose elements from a list using a loop in Python, you can make use of the random.choice() method within a loop. Here's an example code snippet:

main.py
import random

my_list = [1, 2, 3, 4, 5]

for i in range(3):  # choose 3 random elements from my_list
    elem = random.choice(my_list)
    print(elem)
152 chars
8 lines

In this example, the loop iterates 3 times, and each time a random element from my_list is chosen using random.choice(). The chosen element is then printed to the console.

You can modify this code to fit your specific needs, such as changing the number of iterations or the list of elements to choose from.

related categories

gistlibby LogSnag