Python Program to Randomly Select an Element From the List

In this example, you will learn to select a random element from the list.

To understand this example, you should have the knowledge of the following Python programming topics:

1. Example 1: Using random module

1
2
3
4
import random
 
my_list = [1, 'a', 32, 'c', 'd', 31]
print(random.choice(my_list))

Output

1
 

Using random module, we can generate a random element from a list. As shown in the example above, the list my_list is passed as a parameter to choice() method of random module.

Note: The output may vary.

2. Example 2: Using secrets module

1
2
3
4
import secrets
 
my_list = [1, 'a', 32, 'c', 'd', 31]
print(secrets.choice(my_list))

Output

1
c

Using choice() method of secrets module, you can select a random element from the list.

It is cryptographically safer than the random module.