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
1 2 3 4 | import random my_list = [ 1 , 'a' , 32 , 'c' , 'd' , 31 ] print (random.choice(my_list)) |
Output
1 |
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
1 2 3 4 | import secrets my_list = [ 1 , 'a' , 32 , 'c' , 'd' , 31 ] print (secrets.choice(my_list)) |
Output
1 | 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 format()
Python globals()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Count the Number of Digits Present In a Number
Python repr()
Python String replace()
Deep Learning with Python - Francois Chollet
Python Program to Find the Factorial of a Number
Python exec()
Python Program to Compute the Power of a Number
JavaScript Template element
Python Program to Find the Square Root
Python Numbers, Type Conversion and Mathematics
Python Machine Learning Eqution Reference - Sebastian Raschka
Python enumerate()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Dictionary update()
Python sleep()
Python hash()
Python Set clear()
Removing all duplicates from a List in Java
Python Namespace and Scope
Python Program to Find the Factors of a Number
Python Directory and Files Management
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Get the Full Path of the Current Working Directory
Python Program to Check If Two Strings are Anagram
Python String rsplit()
Python sum()
Python Program to Make a Flattened List from Nested List