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 Dictionary values()
Python List remove()
Python Set issubset()
Python frozenset()
Python String startswith()
Python @property decorator
Python Directory and Files Management
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python del Statement
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Type Conversion and Type Casting
Python Program to Make a Flattened List from Nested List
Deep Learning with Python - Francois Chollet
Python String title()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python repr()
Python Program to Check if a Number is Odd or Even
Python String istitle()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python List
Python Closures
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Set symmetric_difference()
Python List reverse()
Python Program to Catch Multiple Exceptions in One Line
Python Set remove()
Python Program to Make a Simple Calculator
Python Deep Learning Cookbook - Indra den Bakker
Python Program to Print Output Without a Newline
Python Program to Create a Long Multiline String