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 Shuffle Deck of Cards
Python format()
Python Functions
Python Program to Measure the Elapsed Time in Python
Python reversed()
Python Matrices and NumPy Arrays
Python Program to Display Fibonacci Sequence Using Recursion
How to Get Started With Python?
Python Numbers, Type Conversion and Mathematics
Python Program to Parse a String to a Float or Int
Python Program to Compute the Power of a Number
Python range()
Python Set issuperset()
Python Namespace and Scope
Python Set remove()
Python Program to Capitalize the First Character of a String
Python String rsplit()
Python Program to Get a Substring of a String
Python Tuple count()
Python Keywords and Identifiers
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Set update()
Python Program to Differentiate Between type() and isinstance()
Python filter()
Python String isprintable()
Copy a List to Another List in Java
JavaScript Template element
Python exec()
Python *args and **kwargs
Python Set discard()
Python Program to Generate a Random Number
Python Set symmetric_difference_update()