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 Set copy()
Python Program to Remove Punctuations From a String
Python List clear()
Python Program to Delete an Element From a Dictionary
Python str()
Python String count()
Python break and continue
Python Set update()
Python String lstrip()
Python String isdigit()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Get a Substring of a String
Python Recursion
Python String rpartition()
Python Program to Get the Last Element of the List
Python divmod()
Python memoryview()
Python Program to Print all Prime Numbers in an Interval
Python Strings
Python Program to Make a Simple Calculator
Python vars()
Python Program to Find Armstrong Number in an Interval
Python String startswith()
Python String islower()
Python Global Keyword
Remove the First Element from a List
Python Program to Multiply Two Matrices
Python Statement, Indentation and Comments
Python Set difference_update()
Python max()
Python delattr()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho