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 bool()
Python complex()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python List index()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python List reverse()
Python List pop()
Python Program to Compute the Power of a Number
Python Tuple
Python List count()
Python Program to Check if a Number is Odd or Even
Python float()
Python Program to Get the Last Element of the List
Python String isdecimal()
Python Dictionary fromkeys()
Python Input, Output and Import
Java List UnsupportedOperationException
Deep Learning in Python - LazyProgrammer
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Get the File Name From the File Path
Deep Learning with Python - Francois Cholletf
Python tuple()
Python Package
Python Program to Display the multiplication Table
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Convert Two Lists Into a Dictionary
Python Program to Transpose a Matrix
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Reverse a Number
Python for Loop
Python Program to Shuffle Deck of Cards
Python Program to Count the Number of Occurrence of a Character in String