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
1 2 3 4 5 6 7 8 9 10 |
import random # Declare List in Python myList = ["one", 11, "Two", 23.9, "Three"] #Select random elements using random.choice() ranElem = random.choice(myList) #Print result print(ranElem) |
Output
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
1 2 3 4 5 6 7 8 9 10 |
import random # Declare List in Python myList = ["one", 11, "Two", 23.9, "Three"] #Get specified random elements using random.sample() ranElem = random.sample(myList, 2) #Print result print(ranElem) |
Output
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
1 2 3 4 5 6 7 8 9 10 |
import secrets # Declare List in Python myList = ["one", 11, "Two", 23.9, "Three"] #Select random elements using secrets.choice() ranElem = secrets.choice(myList) #Print result print(ranElem) |
Output
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
This is so well explained. Thank you