Generating Random Numbers in Python using Random Module

Generating random numbers is a simple process for us. All we have to do is say the first number that comes to our mind. However, doing the same task with computers is more difficult because computers are programmed to follow a set of carefully pre-defined instructions. Thus, in order to produce randomness, computers measure an external phenomenon such as time. Despite the fact that it appears complicated, Python offers a number of libraries that make generating random numbers easier. In this article, we will look at one such library called random.

Importance of Random Numbers

Random numbers play a huge role in:

1. Testing new statistical models
2. Designing cryptography programs
3. Making video games
4. Creating and testing simulations
5. Shuffling and dividing datasets into train and test in Machine Learning programs
6. Programming RNG algorithms for Casinos

Random Module

The random module is a Python built-in module that has numerous classes and methods for generating different sorts of random numbers. It is included in the Python standard library.

Importing Random Module

We need to first import the random module to use it. To import a module, we can use the import keyword.

Example of importing random module in Python

import random
print(dir(random))

Output

[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’, ‘TWOPI’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_accumulate’, ‘_acos’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_log’, ‘_os’, ‘_pi’, ‘_random’, ‘_repeat’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]

In the above code example, we imported the random module and printed a list of all objects present in the random module.

Random floating-point numbers

To generate a random floating-point number, we can use the method random(). This generates a random floating-point number between 0 and 1.

Example of using random() in Python

import random

print(random.random())
print(random.random())
print(random.random())

Output

0.007216975043901286
0.32903515347461554
0.25939499319111203

Generating Floating-point Random Numbers within Range

We can randomly generate a floating-point number within a given range by using the method uniform(a, b). This method returns floating-point numbers between a and b. The arguments for a and b can either be int or float data types.

Example of using uniform() in Python

import random

print(random.uniform(0.5, 2.5))
print(random.uniform(0.5, 2.5))
print(random.uniform(0.5, 2.5))

Output

0.8868252675861883
0.8324629320911934
1.1057420841382244

Generating Random Integers within Range

We can use randint() or randrange() to generate random integers.

random.randint(a, b)

This method generates a random integer between a and b including a and b.

Example of using randint() in Python

import random

print(random.randint(0, 9))
print(random.randint(0, 9))
print(random.randint(50, 100))

Output

3
9
82

random.randrange(start, stop[, step])

This method generates an integer within the passed range. randrange(start, stop) is equivalent to the randint(a, b-1)

Example of using randrange() in Python

import random

print(random.randrange(0, 9))
print(random.randrange(0, 9))
print(random.randrange(50, 100, 2))
print(random.randrange(50, 100, 2))

Output

2
0
92
96

Choosing randomly from a list

We can randomly pick an element from any given list by using the method choice(seq). It takes any non-empty sequence and randomly returns an element from the sequence. It raises IndexError if the sequence is empty.

Example of using choice() in Python

import random

var = [24, 25, "PythonGeeks", "Python"]

print(random.choice(var))
print(random.choice(var))
print(random.choice(var))

Output

PythonGeeks
25
24

Randomly choosing a subset from a list

We can randomly pick multiple elements at once from a list by using the sample(population, k) method. It is useful to generate random subsets from a given set of elements.

Example of using sample() in Python

import random

var = [24, 25, "PythonGeeks", "Python", 4.5, 8.2]

print(random.sample(var, 2))
print(random.sample(var, 3))
print(random.sample(var, 4))

Output

[4.5, 8.2]
[‘Python’, ‘PythonGeeks’, 4.5]
[8.2, ‘Python’, 4.5, 24]

Shuffling a list

Similar to shuffling a pack of cards, we can randomly shuffle a list by using the method shuffle(x). It has no return value and modifies the passed object.

Example of using shuffle() in Python

import random

var = [24, 25, "PythonGeeks", "Python", 4.5, 8.2]

random.shuffle(var)
print(var)
random.shuffle(var)
print(var)
random.shuffle(var)
print(var)

Output

[‘PythonGeeks’, 25, 4.5, ‘Python’, 24, 8.2]
[4.5, 25, ‘PythonGeeks’, 8.2, 24, ‘Python’]
[‘Python’, 24, 4.5, ‘PythonGeeks’, 8.2, 25]

Creating a list with random integers

We can use a for-loop and either randint() or randrange() to create a list of random integers.

Example of creating a list with random integers in Python

import random

numbers = []

for _ in range(10):
    num = random.randrange(10, 100)
    numbers.append(num)

print(numbers)

Output

[47, 10, 46, 52, 47, 35, 66, 39, 99, 82]

In the above code example, we created a list with ten two-digit random numbers.

We can also use list comprehension to make the code smaller and simpler.

Example of creating a list with random integers in Python

import random

numbers = [random.randrange(10, 100) for _ in range(10)]

print(numbers)

Output

[43, 39, 48, 62, 59, 10, 58, 84, 68, 70]

Random Gaussian Values

The method gauss(mu, sigma) takes mean and standard deviation as arguments and returns a randomly generated gaussian distribution.

Example of using gauss() in Python

import random


print(random.gauss(1, 0.5))
print(random.gauss(1, 0.5))
print(random.gauss(1, 0.5))

Output

2.0086156319487296
0.7248870595703139
1.669909507146531

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

When debugging or testing models, we often need to generate the same set of random numbers again and again. To do this, we use the method seed(a). It takes an integer as an argument. If no argument is passed, then it uses the current system time. It has no return value.

Example of using seed() in Python

import random

print("Seed = 3")
random.seed(3)
print(random.random())
print(random.randint(0, 9))
print(random.choice([1, 2, 3, 4]))

print("Seed = 7")
random.seed(7)
print(random.random())
print(random.randint(0, 9))
print(random.choice([1, 2, 3, 4]))

print("Seed = 3")
random.seed(3)
print(random.random())
print(random.randint(0, 9))
print(random.choice([1, 2, 3, 4]))

print("Seed = 7")
random.seed(7)
print(random.random())
print(random.randint(0, 9))
print(random.choice([1, 2, 3, 4]))

Output

Seed = 3
0.23796462709189137
8
2
Seed = 7
0.32383276483316237
2
4
Seed = 3
0.23796462709189137
8
2
Seed = 7
0.32383276483316237
2
4

Python Interview Questions on Generating Random Numbers in Python

Q1. Write a program to randomly generate a three-digit random number.

Ans 1. Complete code is as follows:

from random import randrange

print(randrange(10, 100))

Output

24

Q2. Write a program to randomly generate a floating-point number between 2.5 and 7.3.

Ans 2. Complete code is as follows:

from random import uniform

print(uniform(2.5, 7.3))

Output

5.5440840428887554

Q3. Write a program to print a random value from the list [Phil, Cam, Luke, Lily, jay, Cameron, Michelle].

Ans 3. Complete code is as follows:

from random import choice

names = ["Phil", "Cam", "Luke", "Lily", "jay", "Cameron", "Michelle"]
print(choice(names))

Output

Phil

Q4. Write a program to shuffle the list [4, 5, 6, 7, 8, 9, 10].

Ans 4. Complete code is as follows:

from random import shuffle

names = [4, 5, 6, 7, 8, 9, 10]
shuffle(names)
print(names)

Output

[9, 6, 7, 10, 8, 4, 5]

Q5. Write a program to create a list with 4 random ten-digit integers.

Ans 5. Complete code is as follows:

from random import randrange

integers = [randrange(pow(10, 9), pow(10, 10)) for _ in range(4)]

print(integers)

Output

[9050047497, 1854547528, 3833668794, 8320459476]

Conclusion

In this article, we learned how to generate random numbers. We learned various methods of the random module. We also discussed the importance of random numbers. In addition, if you have any questions, please leave them in the comments area.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *