Random module

Random Module is used to generate random things by applying random function code lines. Learn more about the Random module in python here.

Random module: Creating a random user password

In order to create a random user password we can use the symbols provided in the string module. Specifically punctuation for punctuation symbols, ascii_letters for letters and digits for digits:

from string import punctuation, ascii_letters, digits

We can then combine all these symbols in a name named symbols:

symbols = ascii_letters + digits + punctuation

Remove either of these to create a pool of symbols with fewer elements.

After this, we can use random.SystemRandom to generate a password. For a 10 length password:

secure_random = random.SystemRandom()
password = "".join(secure_random.choice(symbols) for i in range(10))
print(password) # '^@g;J?]M6e'

Note that other routines made immediately available by the random module — such as random.choice, random.randint, etc. — are unsuitable for cryptographic purposes.

Behind the curtains, these routines use the Mersenne Twister PRNG, which does not satisfy the requirements of a CSPRNG. Thus, in particular, you should not use any of them to generate passwords you plan to use. Always use an instance of SystemRandom as shown above.

Python 3.x Version ≥ 3.6

Starting from Python 3.6, the secrets module is available, which exposes cryptographically safe functionality.

Quoting the official documentation, to generate “a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits,” you could:

import string
alphabet = string.ascii_letters + string.digits
while True:
password = ''.join(choice(alphabet) for i in range(10))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break

Random module: Create cryptographically secure random numbers

By default the Python random module use the Mersenne Twister PRNG to generate random numbers, which, although suitable in domains like simulations, fails to meet security requirements in more demanding environments.

In order to create a cryptographically secure pseudorandom number, one can use SystemRandom which, by using os.urandom, is able to act as a Cryptographically secure pseudorandom number generator, CPRNG.

The easiest way to use it simply involves initializing the SystemRandom class. The methods provided are similar to the ones exported by the random module.

from random import SystemRandom
secure_rand_gen = SystemRandom()

In order to create a random sequence of 10 ints in range [0, 20], one can simply call randrange():

print([secure_rand_gen.randrange(10) for i in range(10)])

[9, 6, 9, 2, 2, 3, 8, 0, 9, 9]

To create a random integer in a given range, one can use randint:

print(secure_rand_gen.randint(0, 20))

5

and, accordingly for all other methods. The interface is exactly the same, the only change is the underlying number generator.

You can also use os.urandom directly to obtain cryptographically secure random bytes.

Random module: Random and sequences: shu e, choice and sample

import random

shuffle()

You can use random.shuffle() to mix up/randomize the items in a mutable and indexable sequence. For example a list:

laughs = ["Hi", "Ho", "He"]
random.shuffle(laughs) # Shuffles in-place! Don't do: laughs = random.shuffle(laughs)
print(laughs)
Out: ["He", "Hi", "Ho"] # Output may vary! choice()

Takes a random element from an arbitrary sequence:

print(random.choice(laughs))

Out: He # Output may vary!

sample()

Like choice it takes random elements from an arbitrary sequence but you can specify how many:

|–sequence–|–number–|

print(random.sample( laughs , 1 )) # Take one element

Out: [‘Ho’] # Output may vary!

it will not take the same element twice:

print(random.sample(laughs, 3)) # Take 3 random element from the sequence.

Out: [‘Ho’, ‘He’, ‘Hi’] # Output may vary!

print(random.sample(laughs, 4)) # Take 4 random element from the 3-item sequence.

ValueError: Sample larger than population

Random module: Creating random integers and floats: randint, randrange, random, and uniform

import random

randint()

Returns a random integer between x and y (inclusive):

random.randint(x, y)

For example getting a random number between 1 and 8:

random.randint(1, 8) # Out: 8
randrange()

random.randrange has the same syntax as range and unlike random.randint, the last value is not inclusive:

random.randrange(100) # Random integer between 0 and 99
random.randrange(20, 50) # Random integer between 20 and 49
random.rangrange(10, 20, 3) # Random integer between 10 and 19 with step 3 (10, 13, 16 and 19)

random

Returns a random floating point number between 0 and 1:

random.random() # Out: 0.66486093215306317

uniform

Returns a random floating point number between x and y (inclusive):

random.uniform(1, 8) # Out: 3.726062641730108

Reproducible random numbers: Seed and State

Setting a specific Seed will create a fixed random-number series:

random.seed(5) # Create a fixed state
print(random.randrange(0, 10)) # Get a random integer between 0 and 9 # Out: 9
print(random.randrange(0, 10))

Out: 4

Resetting the seed will create the same “random” sequence again:

random.seed(5)  # Reset the random module to the same fixed state.
print(random.randrange(0, 10))          

Out: 9

print(random.randrange(0, 10))

Out: 4

Since the seed is fixed these results are always 9 and 4. If having specific numbers is not required only that the values will be the same one can also just use getstate and setstate to recover to a previous state:
save_state = random.getstate() # Get the current state
print(random.randrange(0, 10))

Out: 5

print(random.randrange(0, 10))

Out: 8

random.setstate(save_state) # Reset to saved state
print(random.randrange(0, 10))

Out: 5

print(random.randrange(0, 10))

Out: 8

To pseudo-randomize the sequence again you seed with None:

random.seed(None)

Or call the seed method with no arguments:

random.seed()

Random module: Random Binary Decision

import random
probability = 0.3
if random.random() < probability:
print("Decision with probability 0.3")
else:
print("Decision with probability 0.7")

Learn More

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment