Python Random Module Tutorial

In Python, the Random Module serves as an integrated module that allows for the generation of random numbers. This module produces Pseudo-random numbers, indicating that these values are not truly random in nature. Using the Random Module, one can create various random entities such as numbers, strings, or lists within Python.

What is the Seed value in the Python Random Module?

The Seed value represents a numerical input in the Random Module that produces a consistent sequence of Random numbers.

Let’s explore several examples to grasp the application of Seed values within the Python Random Module:

Example: Usage of Seed Values

Example

Example

#importing the random module

import random

#using the seed value set to 1

random.seed(2)

#printing the random numbers

print(random.random())

print(random.random())

print(random.random())

Output:

Output

0.13436424411240122

0.8474337369372327

0.763774618976614

Explanation:

We generated random numbers utilizing a seed value. The outcome remains consistent regardless of how many times the code is executed; it will always produce the same result. Conversely, if you include an additional print(random.random) line, it will yield a different value. When you execute the code again with this new statement added, the output will remain unchanged.

Let’s incorporate an additional print(random.random) statement into this code.

Example

Example

#importing the random module

import random

#using the seed value set to 5

random.seed(5)

print(random.random())

print(random.random())

print(random.random())

#added another random statement

print(random.random())

Output:

Output

0.6229016948897019

0.7417869892607294

0.7951935655656966

0.9424502837770503

#running the code 2nd time

0.6229016948897019

0.7417869892607294

0.7951935655656966

0.9424502837770503

Explanation:

In this example, we have generated random numbers utilizing the Random Module with a seed value of 5. Observably, when we included an additional print(random.random) statement, it resulted in a different random value being produced. However, running the code multiple times will yield the same output each time, demonstrating the effect of the fixed seed.

Functions in the Python Random Module

The Python Random Module offers a diverse set of functions. Let’s examine these functions:

S No. Functions Description
1) seed() It generates a fixed set of random numbers
2) getstate() It gives the current internal state of the random number generator.
3) getrandbits() Generates random number bits
4) randrange() Generates random numbers within a specified range
5) randint() It also generates random numbers within a given range.
6) setstate() It restores the internal state of the random number generator.
7) choice() It gives a random number from a sequence.
8) choices() It gives multiple numbers from a sequence
9) shuffle() This function shuffles the items in a sequence
10) sample() This function returns a given sample of a sequence
11) random() This function returns a random float number between 0 and 1
12) uniform() Returns a random float number between two given parameters
13) triangular() Returns a random float number between two given parameters. You can also set a mode parameter to specify the midpoint between the two other parameters.
14) betavariate() It gives a random float number between 0 and 1 on the basis of the Beta distribution.
15) expovariate() It gives a random float number on the basis of the Exponential distribution.
16) gammavariate() It gives a random float number on the basis of the Gamma distribution.
17) gauss() This function generates a random floating-point number based on the Gaussian distribution.
18) lognormvariate() This function gives a random float number based on a log-normal distribution.
19) normalvariate() This function gives a random float number based on the normal distribution
20) vonmisesvariate() This function returns a random float number based on the Von Mises distribution.
21) paretovariate() This function returns a random float number based on the Pareto distribution.
22) weibullvariate() This function returns a random float number based on the Weibull distribution.

Examples of the Python Random Module

Here are a variety of illustrations showcasing the Python Random Module:

Using the randint function

We can generate and display random integers utilizing the random.randint function. Let’s illustrate this with an example:

Example

Example

#importing the random module

import random

#using the randint() function

n1 = random.randint(1,15)

#printing the random value

print (n1)

Output:

Explanation:

In the preceding example, we have brought in the random module and utilized the randint function to display a random integer within the inclusive range of 1 to 15, encompassing both endpoints.

Using the randrange function

The random integers within a defined range can be generated using the random.randrange function. Additionally, we have the option to specify a step value, which enables us to have greater control over the selection of random numbers at specific intervals. To illustrate this concept, consider the following example:

Example

Example

#importing the random module

import random

#using the randrange()function

n1 = random.randrange(1, 15, 2)

#printing the random value

print (n1)

Output:

Output

#first run

7

#second run

1

#third run

13

Explanation:

In this example, we utilize the randrange function to generate and display a random integer within a defined range, with the step value set to 2. This step value ensures that the random integers produced will be in increments of 2, while also excluding the number 15 from the possible outcomes.

For instance, with a step value of 2, we would obtain numbers exclusively from the following set:

Example

1, 3, 5, 7, 9, 11, 13

Example to Generate a Random Float between 0 and 1

To produce a random floating-point number within the range of 0 to 1, the random function is employed. In our code, we implement it as random.random. Let’s illustrate this with an example:

Example

Example

#importing the random module

import random

#using the random() function

n1 = random.random()

#printing the float number between 0 and 1

print (n1)

Output:

Output

0.6231843843709984

Explanation:

In the preceding illustration, we employed the random function to generate and display a float value that falls between 0 and 1. In terms of code, this is represented as random.random

Example to Randomly Select from List, String, and Tuple

In this section, we will employ the choice function to randomly pick elements from a List, String, and Tuple. To illustrate this concept, let’s look at an example:

Example

Example

#importing the random module

import random

#declaring a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#printing random elements from the list

print(random.choice(my_list))

#declaring a string

my_string = "Example"

#printing random elements from the string

print(random.choice(my_string))

#declaring a tuple

my_tuple = (2, 0, 1, 9)

#printing random elements from the tuple

print(random.choice(my_tuple))

Output:

Output

6

o

9

Explanation:

In this instance, we utilized the random.choice function to obtain random elements from a List, a String, and a Tuple.

Example to Shuffle Elements in a List

The shuffle function serves the purpose of randomly rearranging the positions of elements within a collection. This is accomplished by utilizing the random.shuffle method.

Let’s explore a few instances to understand the functionality of the shuffle method:

Example 1: Shuffling the numbers

To illustrate the process of shuffling numbers within a Python List, let us consider the following example.

Example

Example

#importing the random module

import random

num = [1, 2, 3, 4, 5, 7, 8, 9]

#shuffling the numbers for 1st time

random.shuffle(num)

print("After shuffle : ")

print(num)

#shuffling the numbers for the 2nd time

random.shuffle(num)

print("\nSecond shuffle : ")

print(num)

#shuffling the numbers for the 3rd time

random.shuffle(num)

print("\nThird shuffle : ")

print(num)

Output:

Output

After shuffle :

[3, 9, 7, 8, 1, 4, 2, 5]

Second shuffle :

[8, 3, 1, 7, 9, 5, 4, 2]

Third shuffle :

[7, 2, 4, 8, 9, 5, 3, 1]

Explanation:

In the preceding example, the random.shuffle function was utilized to randomly rearrange or alter the positions of the elements.

In a similar fashion, we can utilize the random.shuffle function to randomly rearrange strings, but this requires placing them into a list first. Let's explore this through an illustrative example below:

Example 2: Shuffling the Strings

The random.shuffle function is utilized to randomly rearrange the order of strings.

Example

Example

#importing the random module

import random

string = ["T", "point", "Tech"]

#shuffling the string for 1st time

random.shuffle(string)

print("After shuffle : ")

print(string)

#shuffling the string for the 2nd time

random.shuffle(string)

print("\nSecond shuffle : ")

print(string)

#shuffling the string for the 3rd time

random.shuffle(string)

print("\nThird shuffle : ")

print(string)

Output:

Output

After shuffle :

['point', 'T', 'Tech']

Second shuffle :

['point', 'Tech', 'T']

Third shuffle :

['T', 'point', 'Tech']

Explanation:

In the previous illustration, we utilized the random.shuffle function, which rearranges the positions of the strings in a random manner after they have been placed into a List. It is important to note that random.shuffle is applicable solely to mutable sequences, such as lists.

Applications of the Python Random Module

There are several applications of the Python Random Module , such as:

  • Generating Random Numbers - This can be used in games or lotteries.
  • Shuffling - It can be used in Card Shuffling and other activities.
  • Creating Random Passwords - We can create Random Passwords, which would enhance the security.
  • Machine Learning and Data Science - Training datasets randomly.
  • Conclusion

The Python Random Module is an integral built-in module that allows for the generation of random numbers. It produces pseudo-random numbers, indicating that these numbers are not genuinely random in nature. The Random Module can create various objects, including numbers, strings, or lists.

The Python Random Module has a variety of applications, including the generation of random numbers, shuffling elements, and the creation of random passwords and PINs. Additionally, it plays a significant role in Machine Learning, where it is utilized to train datasets in randomized manners.

Frequently Asked Questions (FAQs)

1. What is the random module in Python?

In Python, the Random Module is a standard library component that allows us to produce random numerical values.

2. Are Python random numbers really random?

The Random Module produces pseudo-random numbers, indicating that these numbers are, in fact, not truly random.

3. How to generate a random integer in Python?

In Python, the function random.randint(x, y) can be utilized to produce a random integer, with both x and y included in the range of possible outcomes.

4. What is the difference between randrange and randint?

The distinction between the functions randrange and randint is quite subtle. The function random.randint(x, y) encompasses both endpoints, meaning it includes both x and y in its range.

The function random.randrange(x, y, step value) operates similarly to a range function but incorporates step values, with the upper limit y being excluded from the selection.

5. Does random.shuffle work on strings and Tuples?

No, the function random.shuffle is applicable exclusively to mutable sequences, like lists. Nevertheless, strings and tuples can be transformed into lists.

6. How to shuffle a list randomly?

The function random.shuffle( listname ) can be utilized to randomly rearrange the elements of a list.

7. What is the seed function in the random module?

The Seed value is a numeric parameter found in the Random Module that produces a consistent sequence of Random numbers.

Input Required

This code uses input(). Please provide values below: