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 String format()
Python staticmethod()
Python String count()
Python String isprintable()
Python Keywords and Identifiers
Python Program to Display Fibonacci Sequence Using Recursion
Python Dictionary pop()
Python Statement, Indentation and Comments
Python Function Arguments
Python List
Python all()
Python ord()
Python Functions
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Convert String to Datetime
Python String maketrans()
Python Program to Delete an Element From a Dictionary
Python Dictionary copy()
Python Program to Find LCM
Python Program to Compute all the Permutation of the String
Python Set symmetric_difference_update()
Python String rfind()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python String zfill()
Python Program to Represent enum
Python Program to Check Leap Year
Python Program to Find the Sum of Natural Numbers
Python len()
Python Variables, Constants and Literals
Convert a Map to an Array, List or Set in Java
Python Set intersection()
Python Program to Trim Whitespace From a String