Open In App

Random Numbers in Python

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python defines a set of functions that are used to generate or manipulate random numbers through the random module. 

Functions in the random module rely on a pseudo-random number generator function random(), which generates a random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any application requiring a random number generation.

Let us see an example of generating a random number in Python using the random() function.

Python3




import random
num = random.random()
print(num)


Output: 

0.30078080420602904

Different Ways to Generate a Random Number in Python

There are a number of ways to generate a random numbers in Python using the functions of the Python random module. Let us see a few different ways.

Generating a Random number using choice()

Python random.choice() is an inbuilt function in the Python programming language that returns a random item from a list, tuple, or string.

Python3




# import random
import random
 
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
 
# prints a random item from the string
string = "striver"
print(random.choice(string))


Output:

5
t

Generating a Random Number using randrange()

The random module offers a function that can generate Python random numbers from a specified range and also allows room for steps to be included, called randrange().

Python3




# importing "random" for random operations
import random
 
# using choice() to generate a random number from a
# given list of numbers.
print("A random number from list is : ", end="")
print(random.choice([1, 4, 8, 10, 3]))
 
# using randrange() to generate in range from 20
# to 50. The last parameter 3 is step size to skip
# three numbers when selecting.
print("A random number from range is : ", end="")
print(random.randrange(20, 50, 3))


Output: 

A random number from list is : 4
A random number from range is : 41

Generating a Random number using seed()

Python random.seed() function is used to save the state of a random function so that it can generate some random numbers in Python on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator. For the first time when there is no previous value, it uses the current system time.

Python3




# importing "random" for random operations
import random
 
# using random() to generate a random number
# between 0 and 1
print("A random number between 0 and 1 is : ", end="")
print(random.random())
 
# using seed() to seed a random number
random.seed(5)
 
# printing mapped random number
print("The mapped random number with 5 is : ", end="")
print(random.random())
 
# using seed() to seed different random number
random.seed(7)
 
# printing mapped random number
print("The mapped random number with 7 is : ", end="")
print(random.random())
 
# using seed() to seed to 5 again
random.seed(5)
 
# printing mapped random number
print("The mapped random number with 5 is : ", end="")
print(random.random())
 
# using seed() to seed to 7 again
random.seed(7)
 
# printing mapped random number
print("The mapped random number with 7 is : ", end="")
print(random.random())


Output: 

A random number between 0 and 1 is : 0.510721762520941
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237

Generating a Random number using shuffle()

The shuffle() function is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is in place.

Python3




# import the random module
import random
 
 
# declare a list
sample_list = ['A', 'B', 'C', 'D', 'E']
 
print("Original list : ")
print(sample_list)
 
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
 
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)


Output:

Original list : 
['A', 'B', 'C', 'D', 'E']

After the first shuffle : 
['A', 'B', 'E', 'C', 'D']

After the second shuffle : 
['C', 'E', 'B', 'D', 'A']

Generating a Random number using uniform()

The uniform() function is used to generate a floating point Python random number between the numbers mentioned in its arguments. It takes two arguments, lower limit(included in generation) and upper limit(not included in generation).

Python3




# Python code to demonstrate the working of
# shuffle() and uniform()
 
# importing "random" for random operations
import random
 
# Initializing list
li = [1, 4, 5, 10, 2]
 
# Printing list before shuffling
print("The list before shuffling is : ", end="")
for i in range(0, len(li)):
    print(li[i], end=" ")
print("\r")
 
# using shuffle() to shuffle the list
random.shuffle(li)
 
# Printing list after shuffling
print("The list after shuffling is : ", end="")
for i in range(0, len(li)):
    print(li[i], end=" ")
print("\r")
 
# using uniform() to generate random floating number in range
# prints number between 5 and 10
print("The random floating point number between 5 and 10 is : ", end="")
print(random.uniform(5, 10))


Output: 

The list before shuffling is : 1 4 5 10 2 
The list after shuffling is : 2 1 4 5 10 
The random floating point number between 5 and 10 is : 5.183697823553464


Similar Reads

Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Python - Random Numbers Summation
Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers and perform its summation. This task has to performed in general using loop and appending the random numbers one by one and then performing sum. But there is always requirement to perform this in most concise manner. Lets discu
4 min read
How to generate random numbers from a log-normal distribution in Python ?
A continuous probability distribution of a random variable whose logarithm is usually distributed is known as a log-normal (or lognormal) distribution in probability theory. A variable x is said to follow a log-normal distribution if and only if the log(x) follows a normal distribution. The PDF is defined as follows. Where mu is the population mean
3 min read
Generate five random numbers from the normal distribution using NumPy
In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distrib
2 min read
How to Draw Binary Random Numbers (0 or 1) from a Bernoulli Distribution in PyTorch?
In this article, we discuss how to draw Binary Random Numbers (0 or 1) from a Bernoulli Distribution in PyTorch. torch.bernoulli() method torch.bernoulli() method is used to draw binary random numbers (0 or 1) from a Bernoulli distribution. This method accepts a tensor as a parameter, and this input tensor is the probability of drawing 1. The value
2 min read
Generate random numbers and background colour in Django
In this article, we will learn how to generate random numbers and background colors in Python Django. And we will also see different steps related to a random number in Django. These are the following steps that we are going to discuss in this tutorial: What is the Django?Functions to generate a random numberFunctions to generate random background
4 min read
Generate Random Numbers From The Uniform Distribution using NumPy
Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. Syntax: numpy.random.uniform(low = 0.0, high = 1.0, size = None
1 min read
Article Tags :
Practice Tags :