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 Program to Convert String to Datetime
Python callable()
Python Program to Concatenate Two Lists
Python Variables, Constants and Literals
Python Dictionary copy()
Python String join()
Python Program to Find the Sum of Natural Numbers
Python String upper()
Python Program Read a File Line by Line Into a List
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Find All File with .txt Extension Present Inside a Directory
How to get current date and time in Python?
Python Object Oriented Programming
Python Program to Find the Largest Among Three Numbers
Python format()
Python Sets
Python Tuple count()
Python Program to Reverse a Number
Python String format()
Python Set difference()
Python break and continue
Python divmod()
Python Functions
Python Program to Solve Quadratic Equation
Remove All Occurrences of a Specific Value from a List
Python open()
Python Program to Sort a Dictionary by Value
Python bytes()
Python Type Conversion and Type Casting
Python Set copy()
Python enumerate()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...