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 String format()
Python ascii()
Python property()
Python Modules
How to get current date and time in Python?
Python Program to Shuffle Deck of Cards
Python any()
Python Dictionary popitem()
Python Set difference_update()
Python String count()
Python Program to Convert Kilometers to Miles
Python Dictionary update()
Python Program to Solve Quadratic Equation
Python List
Python String strip()
Python reversed()
Python Program to Catch Multiple Exceptions in One Line
Python Program to Get File Creation and Modification Date
Python hex()
Python Program to Check If a List is Empty
Removing all Nulls from a List in Java
Python Program to Generate a Random Number
Python Closures
Python *args and **kwargs
Python Iterators
Python Program to Return Multiple Values From a Function
Python Set pop()
Python complex()
Python isinstance()
Converting a List to String in Java
Python Set update()
How to Get Started With Python?