Algorithm
-
Using
random.choice()
function:- Call the
random.choice()
function with the given list as an argument. - The function internally selects a random element from the list and returns it.
- Call the
-
Using
random.randint()
to generate a random index:- Use
random.randint()
to generate a random index within the range of list indices. - Access the list element at the randomly generated index.
- Use
-
Using
random.sample()
for a sample of size 1:- Call
random.sample()
with the given list and a sample size of 1. - The function returns a list containing the randomly selected element.
- Call
-
Using
numpy.random.choice()
from NumPy library:- Use
numpy.random.choice()
with the given list as an argument. - The function internally selects a random element from the list and returns it.
- Use
-
Shuffling the list and selecting the first element:
- Use
random.shuffle()
to shuffle the elements of the list in-place. - Access the first element of the shuffled list, which is now randomly selected.
- Use
Code Examples
#1 Code Example- Using random module
Code -
Python Programming
import random
my_list = [1, 'a', 32, 'c', 'd', 31]
print(random.choice(my_list))
Copy The Code &
Try With Live Editor
Output
31
#2 Code Example- Using secrets module
Code -
Python Programming
import secrets
my_list = [1, 'a', 32, 'c', 'd', 31]
print(secrets.choice(my_list))
Copy The Code &
Try With Live Editor
Output
c
Demonstration
Python Programing Example to Randomly Select an Element From the List-DevsEnv