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 eval()
Python Objects and Classes
Python Dictionary
Debug a JavaMail Program
Python Program to Copy a File
Python Set difference_update()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Slice Lists
Python String casefold()
Python Dictionary popitem()
Python Program to Multiply Two Matrices
Python vars()
Python Program to Print all Prime Numbers in an Interval
How to Get Started With Python?
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python String maketrans()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String islower()
Python next()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Strings
Python Program to Find Numbers Divisible by Another Number
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python String isalpha()
Python Directory and Files Management
Python Program to Find HCF or GCD
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python pass statement
Python Program to Reverse a Number
Removing all duplicates from a List in Java
Python Variables, Constants and Literals