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 Solve Quadratic Equation
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String isdecimal()
Python break and continue
Python hex()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Converting between an Array and a List in Java
Python str()
Python Program to Illustrate Different Set Operations
Python Dictionary update()
Python bin()
Python Modules
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Display Fibonacci Sequence Using Recursion
Python zip()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Set symmetric_difference_update()
Python List append()
Python Program to Get the File Name From the File Path
Python Numbers, Type Conversion and Mathematics
Python Recursion
Python Program to Find the Factors of a Number
Python Program to Return Multiple Values From a Function
Python Get Current time
Python Program to Get File Creation and Modification Date
Python memoryview()
Python Anonymous / Lambda Function
Python min()
Python input()
Python locals()
Python Tuple index()
Python abs()