Table of Contents
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
import random my_list = [1, 'a', 32, 'c', 'd', 31] print(random.choice(my_list))
Output
31
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
import secrets my_list = [1, 'a', 32, 'c', 'd', 31] print(secrets.choice(my_list))
Output
c
Using choice() method of secrets module, you can select a random element from the list.
It is cryptographically safer than the random module.
Related posts:
Python Program to Swap Two Variables
Python Dictionary values()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Represent enum
Python Set symmetric_difference()
Python bytearray()
Python Namespace and Scope
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Check If a List is Empty
Deep Learning with Python - Francois Chollet
Python Program to Find Numbers Divisible by Another Number
Python hasattr()
Python object()
Python String isalpha()
Python Program to Access Index of a List Using for Loop
Python sorted()
Python String format()
Python hash()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python pass statement
Python String strip()
Python Program to Find Armstrong Number in an Interval
Copy a List to Another List in Java
Python Program to Check If a String Is a Number (Float)
Python bin()
Converting Iterator to List
Python Get Current time
Python Program to Find LCM
Python List append()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Set update()
Python Program to Display Calendar