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 List copy()
Python Program to Find LCM
Python Program to Convert String to Datetime
Python String expandtabs()
Python Objects and Classes
Python Type Conversion and Type Casting
Deep Learning in Python - LazyProgrammer
Python range()
Python Program to Convert Bytes to a String
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python map()
Python break and continue
Python setattr()
Python __import__()
Python Dictionary keys()
Converting a List to String in Java
Python Dictionary popitem()
Python Machine Learning - Sebastian Raschka
Python Program to Represent enum
Python Set clear()
Python ord()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Deep Learning Cookbook - Indra den Bakker
Python pass statement
Python Program to Find Numbers Divisible by Another Number
Python delattr()
Python String zfill()
Python frozenset()
Python oct()
Python isinstance()
Python Dictionary fromkeys()
Python Set issubset()