How to Randomly Select Element From List in Python

Last Updated on June 18, 2021 by Roshan Parihar

In this tutorial, learn how to randomly select element from List in Python. The short answer is to use the random.choice() function and pass the List variable as its argument. It requires importing the function before using it on your coding.

You can also select the specified number of random elements from the List using Python. The selected random elements can not be the same as it is selected randomly that is different all the time.

Let’s find out the different methods and examples given below and the random output generated by them.

Method 1: Using random.choice() to Randomly Select Element From List in python

To select random elements from List, you can use the random.choice() function that takes a single argument. The argument is the List variable from where you have to select items randomly. You also need to import the function to use it.

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.

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

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

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

Output

[‘Two’, 11]

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

Method 3: Using secrets.choice() 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.

Output

Three

The output shows the single random element selected from the List variable. On each execution of the above code, it gives different element in the output as they are selected randomly from 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.