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 issuperset()
Python Program to Extract Extension From the File Name
Python Program to Count the Number of Each Vowel
Python Strings
Python chr()
Ways to Iterate Over a List in Java
Python Program to Check Leap Year
Python Program to Convert Kilometers to Miles
Python String replace()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python filter()
Python Program to Display the multiplication Table
Python Program to Reverse a Number
How to Find an Element in a List with Java
Python input()
Python String strip()
Python Program to Merge Two Dictionaries
JavaScript Element size and scrolling
Python Program to Find Hash of File
Python pow()
Python String isidentifier()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python List index()
Node.js vs Python for Backend Development
Python Program to Calculate the Area of a Triangle
Python any()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python help()
Python Program to Access Index of a List Using for Loop
Python staticmethod()
Python Program to Generate a Random Number