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 bool()
Python Program to Copy a File
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Multiple Inheritance
Python Set add()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Operators
Python Program to Find LCM
Python set()
Python complex()
Python classmethod()
Python String isspace()
Python File I/O Operation
Python Program to Differentiate Between type() and isinstance()
Python String expandtabs()
Python float()
Python Deep Learning Cookbook - Indra den Bakker
Python Generators
Converting Iterator to List
Python String center()
Ways to Iterate Over a List in Java
Python Program to Compute the Power of a Number
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Sort Words in Alphabetic Order
Python Program to Print the Fibonacci sequence
Python timestamp to datetime and vice-versa
Python Program to Count the Number of Each Vowel
Python Program to Transpose a Matrix
Python Program to Find the Factors of a Number
Python slice()
Python List copy()