How to Select Random Element From List in Python

Last Updated on May 10, 2024 by Roshan Parihar

To select a random element from List in Python, use the random.choice() function and pass the List variable as its argument.

You can also use the secrets.choice() function to get random elements from a List in Python. Let’s find out with the examples given below.

Select Random Element from List Using random.choice() in python?

If you want to select a random element from the List, you can use the random.choice() function. It requires only a single argument as the List variable to pass.

Example 1

Output

Two

The above example shows a single element in the output that is selected randomly from List in Python. One each time you run the code, it gives different elements in the output selected randomly. You cannot identify which element it selects next time when you run the code.

Using random.sample() to Get Specified Random Elements From List in python

When you have to select the randomly specified number of elements from the List, you can use the random.sample() function in Python. It takes two arguments in which the first is the List variable and the second is the number of elements to select.

Example 2

Output

[‘Two’, 11]

The above output shows that it is a List that is created by randomly selected elements from the List variable.

There is no sequence of elements it selects from the List variable. It also gives another list in the output whether you specify any number of elements to select from the List.

Using secrets.choice() Function in Python

In addition to the above methods, you can also use the secrets.choice() function of Python to get random elements from List. It takes a single argument as the List variable to get random elements from it.

Example 3

Output

Three

The output shows the single random element selected from the List variable. Each execution of the above code gives a different element in the output as they are selected randomly from the List.

You May Also Like to Read

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.