W3docs

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.

You can use the random module's choice function to select a random element from a list. Here's an example:

Select a random element from a list using the choice method from the random module

python— editable, runs on the server

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:

Select a random element from a list using the sample method from the random module

python— editable, runs on the server

This will print out a list containing three random elements from my_list.