Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

How to Select a Random Item from a List in Python

There is a very simple way to select a random item or element from a list in Python. For doing this, we have a very important and commonly used module called random. After importing random module, you can use random.choice() method to choose randomly element from the list. Let’s explain it with example

Selecting a Random Item from list in Python by Using random.choice() Method


Output:
The output of this code may be different every time when you execute the code.

3

Choosing a random item from list in Python by using secrets.choice() Method

secrets.choice() is a new method. This function is introduced in Python 3.6. It securely chooses a random number out of a given non-empty sequence such as list. Look at the following code snippet.

Output:
The output of this code may be different every time when you execute the code.

b

 

Difference between secrets.choice() and random.choice() in Python

The secrets module provides the same interface as random. The underlying random generator functionality has just been changed to SystemRandom which is cryptographically stronger than of random module. The secrets module uses highest-quality sources provided by the operating system. On different operating systems, this may provide different results.

Generate secure random numbers for managing secrets“. It is suitable for managing data such as passwords, account authentication, security tokens, and related secrets. In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modeling and simulation, not security or cryptography.

Reference: Python documentation

In short, use secrets as you would use the random module in circumstances that require a bit more security. It is noticed that secrets.choice() suffers from the performance. No doubt, security comes in some performance trade. In general, you can almost achieve same results from both if you ignore some security issues.

 

LearnAndLearn.com © 2018 - All rights reserved