Home Python Python Random Module

Python Random Module

Python’s Random module is a built-in module for generating random integers in Python. These are pseudo-random numbers, which do not represent true randomness. This module can generate random numbers, output a random value for a list or string, and so on. The Random module has various modules in Python. Here, we list some of these functions and explain how they are used.

  • seed() – It is responsible for initializing the random number generator
  • getstate() – It returns an object with the current internal state of the random number generator
  • setstate() – Used to restore the state of the random number generator back to the specified state
  • getrandbits() – Returns an integer with a specified number of bits
  • randrange() – Returns a random number within the range
  • randint() – Returns a random integer within the range
  • choice() – Returns a random item from a list, tuple, or string
  • choices() – Returns multiple random elements from the list with replacement
  • sample() – Returns a particular length list of items chosen from the sequence
  • random() – Generate random floating numbers
  • uniform() – Return random floating number between two numbers, both inclusive
  • triangular() – Return a random floating point number within a range with a bias towards one extreme
  • betavariate() – Return a random floating-point number with beta distribution
  • expovariate() – Return a random floating-point number with exponential distribution
  • gammavariate() – Return a random floating-point number with gamma distribution
  • gauss() – Return a random floating-point number with Gaussian distribution
  • lognormvariate() – Return a random floating-point number with log-normal distribution
  • normalvariate() – Return a random floating-point number with normal distribution
  • vonmisesvariate() – Return a random floating-point number with von Mises distribution or circular normal distribution
  • paretovariate() – Return a random floating-point number with Pareto distribution
  • weibullvariate() – Return a random floating-point number with Weibull distribution

Printing a random value from a list

import random

# prints a random value from the list

my_list = [11, 12, 13, 14, 15, 16]
print(random.choice(my_list ))
Printing a random value from a list
Printing a random value from a list

As mentioned previously, the random module generates pseudo-random numbers. The seeding value determines the randomness of the numbers. If the seeding value is 4, for example, the output of the following program will always be the same.

Making random numbers with a seeding value

import random

random.seed(4)

print(random.random())
print(random.random())
Making random numbers with a seeding value
Making random numbers with a seeding value

The above code will always produce the same result. As a result, it cannot be utilized for encryption. Let’s look at some of the most typical activities this module performs.

Creating Integers at Random

The random.randint() method generates random numbers within a specified range.

The syntax is as follows:

randint(start, end)

Example: How to create random integers

# A program showcasing the work
# of randint() functioning

# here, import the random module as follows
import random

# We need to generate random values  between
# some specified positive range
random_vals = random.randint(21, 35)
print("Random numbers ranging from 21 to 35 is % s" % (r
andom_vals))

# The following example will generate a random number between
# negative range
s as follows 
random_vals = random.randint(-18, -8)
print("Random numbers from -18 and -8 is % d" % (random_vals))

Making Unpredictable Floats

The random.random() method generates random floats in the range of 0.0 to 1.

The syntax is as follows:

random.random()
# Example program demonstrating
# the use of the random() function.
	
# import random
from random import random
	
# Prints random item
print(random())
Making Unpredictable Floats
Making Unpredictable Floats

Random Elements Selection

The random.choice() function returns a random item from a list, tuple, or string.

The syntax is as follows:

random.choice(sequence)

Example: Choosing elements at random from a list, string, or tuple

# example program demonstrating the use of
# choice() method in practice

# import random
import random

# prints a random value from the list
my_list = [11, 12, 13, 14, 15, 16]
print(random.choice(
my_list))

# prints a random item from the string
string_var = "codeunderscored"
print(random.choice(string_var))

# prints a random item from the tuple
test_tuple = (11, 12, 13, 14, 15)
print(random.choice(test_tupl))

Randomly shuffling the list

To shuffle a sequence, use the random.shuffle() method . The term “shuffle” refers to the process of moving the sequence’s parts around. The shuffle operation is in place here.

The syntax is as follows:

random.shuffle(sequence, function)

Example: Shuffling a List as an Example

# import the random module
import random


# declare a list
the_actual_list = [11, 12, 13,14, 15]

print("Original list : ")
print(the_actual_list)

# first shuffle
random.shuffle(the_actual_list)
print("\nAfter the first shuffle : ")
print(the_actual_list)

# second shuffle
random.shuffle(the_actual_list)
print("\nAfter the second shuffle : ")
print(the_actual_list)

Create a range of random numbers

The random.randrange() method selects an element at random from the range defined by the start, stop, and step arguments. By default, the beginning is set to 0. Similarly, the default value of the step is 1.

import random

random.randrange(8, 23)
random.randrange(1, 15, 2)
random.randrange(0, 250, 10)
Create a range of random numbers
Create a range of random numbers

Choose Elements at Random

The random.choice() method selects an element from a non-empty sequence at random. An IndexError is thrown when the argument is an empty sequence.

import random
random.choice('codeunderscored')
random.choice([22,33,55,77,75,53])
random.choice((22,33,55,77,75,53))
Choose Elements at Random
Choose Elements at Random

Randomly shuffle the elements

The random.shuffle() method shuffles the entries in a list at random.

num_vals=[22,33,55,77,75,53]
random.shuffle(num_vals)
num_vals
random.shuffle(num_vals)
num_vals
Randomly shuffle the elements
Randomly shuffle the elements

Conclusion

You can generate random numbers with Python’s built-in package. The random module in Python is used to create random numbers. These are pseudo-random numbers since the seed determines the sequence of numbers generated. The sequence will be the same if the seeding value is the same.

Several methods in the random module are listed in the previous sections above.

For various distributions, this module implements pseudo-random number generators. There is a uniform selection from a range for integers. A method to construct a random permutation of a list in-place and a function for random sampling without replacement are all available for sequences.

Uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions can all be computed on the real line. Also, the von Mises distribution is used to generate angle distributions.

You may also like

Leave a Comment