
- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Random Module
The random module is a standard library module that offers functions for various operations such as random number generation, shuffling sequences, and making random selections. In this module, we will examine the features of the Python random module and provide real-world examples to demonstrate how to use it.
While developing applications, the utilization of python "random" module becomes vital for tasks such as statistical analysis, games, securing cryptographic keys for sensitive data etc. Let us navigate through some of the spectrum of methods with different types of data.
In case of integers there is a uniform selection from a range achieved by randint() and, randrange() functions, where the function randomly selects an integer within a specified range, ensuring that each integer between that range has an equal probability of being chosen.
In case of sequential data like list, tuple, or any other iterable, we can achieve the same functionality through functions like choice(), choices(), etc. Almost all the inbuilt functions of the random module depends on the basic function random.random(), which generates a random float value.
In the realm of statistical analysis, various distributions such as Gaussian distribution, Uniform distribution, Lognormal distribution are used draw the insights for the data. The random module provides functions to generate samples from these distributions.
We do know that random module provides various functions for generating random numbers, however, what may not be apparent is that these functions are bound methods of a hidden instance of the random.Random class. This means, python creates an instance of the Random class and binds the functions to that instance.
Python random.Random class
The Random class executes the default pseudo-random number generator which is used by the random module. The constructor random.Random([seed]) is responsible for creating an instance of the Random class, further allowing for the initialization of a random number generator.
The seed determines the starting point for generating random numbers. Functions such as getstate() and setstate() allows us to access and update the internal state of the generator, which enables the preservation and restoration of the sequences.
Python random.SystemRandom Class
Random module not only provides Random class for random number generation, it also provides the SystemRandom class which is designed to use the system-provided source to generate random numbers. This class uses os.urandom() function which generates cryptographically secured bytes and random numbers.
Let us see various functions in random module.
Functions for Integers
Following are the functions specifically designed for working with integers −
Sr.No. | Function & Description |
---|---|
1 | Python random.randrange([start,] stop [,step]) function This function returns a randomly selected element from the specified range. |
2 | Python random.randint(a,b) function This function accepts two parameters and returns an integer from the range between those parameters (inclusive). |
3 | Python random.getrandbits(a) function This function returns a non-negative integer with a random bits. |
4 |
A random float r, such that 0 is less than or equal to r and r is less than 1 |
Functions for Sequences
Following are the functions specifically designed for working with sequences −
Sr.No. | Function & Description |
---|---|
1 | Python random.choice(seq) function This function accepts a sequence and returns a randomly element from that sequence. |
2 | Python random.choices() function This function returns a list of particular size from a given sequence with replacement. |
3 | Python random.shuffle(seq) function This function shuffles an immutable sequence and returns a new shuffled sequence. |
4 | Python random.sample() function This function returns list of particular size from a given sequence without any replacement. |
Functions for Distributions
Following are the functions specifically designed for working with distributions −
Sr.No. | Function & Description |
---|---|
1 | Python random.binomialvariate(n,p) function This function returns an integer value representing the no:of successes observed for n trails with a probability p. |
2 | Python random.uniform(a, b) function This function returns a random float value between a, b (inclusive). |
3 | Python random.triangular(a,b,mode) function This function returns a float value between a,b both inclusive with a specified mode between the bounds. |
4 | Python random.betavariate() function This function returns a random variate which follows beta distribution. |
5 | Python random.expovariate(lambd=) function If the parameter lambd is positive, the function returns a value ranges from 0 to positive infinity. If lambd is negative, it returns a value between negative infinity and 0. |
6 | Python random.gammavariate(alpha,beta) function This function returns a random variate which follows gamma distribution with shape parameter alpha and scale parameter beta. |
7 | Python random.gauss(mu,std) function This function returns a random variate which follows gaussian distribution with mean "mu" and standard deviation "std". |
8 | Python random.lognormvariate(mu,std) function This function returns a random variate which follows log norm distribution with mean "mu" and standard deviation "std". |
9 | Python random.normalvariate(mu,std) function This function returns a random variate which follows normal distribution with mean "mu" and standard deviation "std". |
10 | Python random.vonmisesvariate(mu,kappa) function This function returns a random variate which follows von Mises distribution with mean angle mu and concentration parameter which measures the dispersion of the distribution. |
11 | Python random.paretovariate(alpha) function This function returns a random variate which follows pareto distribution with shape parameter alpha. |
12 | Python random.weibullvariate(alpha, beta) function This function returns a random variate which follows weibull distribution with shape parameter alpha and scale parameter beta. |
Functions for Bytes
Following are the functions specifically designed for working with bytes −
Sr.No. | Function & Description |
---|---|
1 | Python random.randbytes(a) function This function is used to generate a random bytes. |
Functions for Alternative Generators
Following are the functions specifically designed for alternative generators −
Sr.No. | Function & Description |
---|---|
1 | Python random.seed([x]) function This function initializes the random number generator's internal state. |
2 | Python random.getstate() function This function returns the internal state of the generator. |
3 | Python random.setstate() function This function sets the internal state of the random number generator. |