Introduction

A random sequence of events, symbols or steps often has no order and does not follow an intelligible pattern or combination. A random number generator is a system that generates random numbers from a true source of randomness. Pseudo random numbers is a sample of numbers that look close to random, but are generated using a deterministic process.

Random module in Python offers a suite of functions to generate random numbers. These are pseudo-random number as the sequence of number generated depends on the seed. If the seeding value is same, the sequence will be the same.

Generating Random Number

random() function from Random module can be used to generate random number. It return the next random floating point number in the range [0.0, 1.0). To generate a random number between range, we cab use uniform(). Syntax is

random.uniform(a, b)

It return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

import random

# Generate a random number
print(random.random())

# Output
# 0.21362700222627784

# Generate random number within a range
print(random.uniform(1, 100))

# Output
# 61.01519070272682

Integer Random Number

To generate integer random integer use below functions

  • random.randrange(stop)
  • random.randrange(start, stop[, step]) : Return a random integer number N such that start <= N <= stop. Step decides the difference between consecutive random number.
  • random.randint(a, b) : Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
import random

# Generate random integers within a given range
print(random.randint(1, 100))

# Output
# 47

# Generate random integers with a step function
print(random.randrange(0, 101, 5))

# Output
# 55

Using Seed

Pseudorandom number generator is a mathematical function that takes a parameter to start off the sequence, called the seed. The function is deterministic, meaning given the same seed, it will produce the same sequence of numbers every time. The choice of seed does not matter.

The seed() function will seed the pseudorandom number generator, taking an integer value as an argument. If the seed() function is not called prior to using randomness, the default is to use the current system time.

random.seed(a=None, version=2)

The example below demonstrates seeding the pseudorandom number generator. Using same seed in the generator, result in the same sequence of numbers being generated again.

import random

# Use the seed function to position the generator
random.seed(1)
print(random.random())
print(random.random())

# Output
# 0.13436424411240122
# 0.8474337369372327

random.seed(1)
print(random.random())
print(random.random())

# Output
# 0.13436424411240122
# 0.8474337369372327

Random Element from Sequence

There are three basic sequence types i.e. lists, tuples, and range objects. Random numbers can be used to randomly choose an item from a list. choice() function is use it to randomly select an item from the list. Selections are made with a uniform likelihood. Syntax of choice() function is

random.choice(seq)
random.choices(seq, weights=None, *, cum_weights=None, k=1)

First one return a random element from the non-empty sequence seq. Second one return a k sized list of elements chosen from the seq with replacement. If optional parameter weights is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights.

# Functions for generating random data sequences
import random
import string

# Randomly select from a sequence
moves = ["pen", "paper", "pencil"]
print(random.choice(moves))

# Output
# pencil

# Create a list of random elements
color = ["black", "red", "green"]
weights = [18, 18, 2]
print(random.choices(color, weights, k=10))

# Output
# ['red', 'red', 'black', 'red', 'black', 'black', 'black', 'black', 'red', 'black']

Sample from Sequence

To random subsample from a sequence without replacement use sample() function. Once an item is selected from the list and added to the subset, it should not be added again. This is called selection without replacement. Syntax of sample() function is

random.sample(seq, k)

It return a k length list of unique elements chosen from the sequence or set. If the sample size is larger than the sequence size, a ValueError is raised.

The example below demonstrates selecting a subset of six items from a list of alphabet.

# Functions for generating random data sequences
import random

# Randomly selects elements from sequence
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"]
chosen = random.sample(alphabet, 6)
print(chosen)

# Output
# ['E', 'C', 'D', 'J', 'H', 'A']

Shuffle a Sequence

shuffle() function can be used to shuffle a sequence. This function shuffle the list in place i.e. the list provided as an argument to the function is shuffled rather than a shuffled copy of the list being made and returned. Syntax of shuffle() is

random.shuffle(x[, random])

Optional argument random is a 0-argument function returning a random float in [0.0, 1.0). By default, this is the function random().

The example below demonstrates shuffling a list.

# Functions for generating random data sequences
import random
import string

# Shuffles sequence in place
vowel = ["A", "E", "I", "O", "U"]
random.shuffle(vowel)
print(vowel)

# Output
# ['I', 'A', 'U', 'O', 'E']