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 print()
Python String rpartition()
Python Program to Extract Extension From the File Name
Python Program to Get File Creation and Modification Date
Python staticmethod()
Python List sort()
Python String isidentifier()
Python Program to Multiply Two Matrices
Python Program to Get the Full Path of the Current Working Directory
Python Program to Print Hello world!
Python super()
Python Modules
Python String casefold()
Python Program to Print the Fibonacci sequence
Python sorted()
Python String lstrip()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python String splitlines()
Python sum()
Python help()
Python Program to Find the Factorial of a Number
Python repr()
Python Program to Count the Number of Each Vowel
Python Program to Display Powers of 2 Using Anonymous Function
Python pow()
Python pass statement
Python frozenset()
Python Set copy()
Python Tuple count()
Python Program to Sort Words in Alphabetic Order
Python Program to Print all Prime Numbers in an Interval
Python Program to Check Prime Number