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:
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Remove the First Element from a List
Python Program to Make a Flattened List from Nested List
Python getattr()
Python Dictionary popitem()
Python set()
Python String rsplit()
Python Closures
Copy a List to Another List in Java
Python String format()
Python Set symmetric_difference()
Python Program to Sort a Dictionary by Value
Python Program to Display Powers of 2 Using Anonymous Function
Python String rindex()
Python Set add()
Python __import__()
Python hasattr()
Python String rpartition()
Python iter()
Python String index()
Python sum()
Python String isalnum()
Intelligent Projects Using Python - Santanu Pattanayak
Python String lstrip()
Python Program to Get Line Count of a File
Python Program to Find the Size (Resolution) of a Image
Python Dictionary keys()
Ways to Iterate Over a List in Java
Python Program to Get a Substring of a String
Python Program to Display Fibonacci Sequence Using Recursion
Python Dictionary fromkeys()