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 Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Matrices and NumPy Arrays
Python enumerate()
Python Statement, Indentation and Comments
Python Directory and Files Management
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python strftime()
Python Dictionary
Python Dictionary popitem()
Python Sets
Python Program to Check Leap Year
Python globals()
Python String partition()
Python Program to Check If Two Strings are Anagram
Python open()
Python Set isdisjoint()
Python Program to Differentiate Between del, remove, and pop on a List
Python Tuple
Python Strings
Python Set issuperset()
Python Dictionary fromkeys()
Python Program to Copy a File
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Concatenate Two Lists
Python List extend()
Python String isidentifier()
Python String format_map()
Python List Comprehension
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python bytearray()
Python iter()