Algorithm


  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

 

 

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

x
+
cmd
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

x
+
cmd
c
Advertisements

Demonstration


Python Programing Example to Randomly Select an Element From the List-DevsEnv