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 for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Concatenate Two Lists
Python Decorators
Python Program to Convert Celsius To Fahrenheit
Python Program to Find the Largest Among Three Numbers
Python enumerate()
Converting Between a List and a Set in Java
Python Matrices and NumPy Arrays
Python Program to Find the Factors of a Number
Python int()
Python String format_map()
Python sorted()
Python Program to Remove Duplicate Element From a List
Python Strings
Python Program to Check Leap Year
Python String lower()
Python bytes()
Python open()
Python Program to Trim Whitespace From a String
Python Set union()
Python Program to Merge Two Dictionaries
Python List index()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Create a Countdown Timer
Python Program to Count the Number of Occurrence of a Character in String
Python format()
Python Program to Sort Words in Alphabetic Order
Python String rfind()
Python Dictionary copy()
Python Variables, Constants and Literals
Python Set symmetric_difference()
Python hasattr()