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 Global Keyword
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Check If a String Is a Number (Float)
Python exec()
Python Shallow Copy and Deep Copy
Python set()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python break and continue
Python Dictionary keys()
Python int()
Python Program to Multiply Two Matrices
Python property()
Python delattr()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Split a List Into Evenly Sized Chunks
Python super()
Python Program to Capitalize the First Character of a String
Python bool()
Python Program to Safely Create a Nested Directory
Python String split()
Python Dictionary pop()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Global, Local and Nonlocal variables
Ways to Iterate Over a List in Java
Python slice()
Python object()
Python globals()
Python Program to Check Prime Number
Python Program to Merge Two Dictionaries
Python Program to Sort Words in Alphabetic Order
Python Program to Check Whether a String is Palindrome or Not
Python Closures