Python random Module with Examples

Python random Module: In this tutorial, we are going to learn about the random module with its methods and examples in the Python programming language. By Bipin Kumar Last updated : June 21, 2023

What is Python random Module?

The random module provides us the various functions that use for various operations such as to generate the random number. It is an inbuilt module in Python so there is no need for installation. To use this module in the program, we just need to import it into the program like the other Python module. This module is mostly used when we have to pick a random number from the given list or range. Let's see some important functions of the random module with the example that helps us a lot to understand it in a simple way.

Most Useful Methods of Python random Module

random.randint()

This function used to get a random number between the two given numbers. This function takes two values which one is a lower limit and another one is the upper limit. Let's look at an example which more clear it.

Example

# importing the module
import random

print('A random integer is:')
# lower limit=1 and higher limit=10
print(random.randint(1,10)) 

Output

RUN 1:
A random integer is:
7

RUN 2:
A random integer is:
8

RUN 3:
A random integer is:
6

random.choice()

This function returns a random value from a list which may be an integer or a float value or string. It takes a list as an argument and like the randint() function it also gives a different value from the given list for each test case.

Example

# importing the module
import random

# declaring a list
A=[1,2,5,'Bipin','kumar',3.5,'include','help']

# printing a random element from the list
print('A random value from the given list:')
print(random.choice(A))

Output

RUN 1:
A random value from the given list:
2

RUN 2:
A random value from the given list:
3.5

RUN 3:
A random value from the given list:
help

random.shuffle()

This function is used to mix the elements of the given list in random order. It takes a list as an argument and like other functions of the random module when we run the above program then we will get a different list for each test case.

Example

# importing the function from the module
from random import shuffle

# declaring a list
# same list of the above program
A=[1,2,5,'Bipin','kumar',3.5,'include','help'] 

# shuffling of the element.
shuffle(A) 
print('New list after shuffling the given list:',A)

Output

New list after shuffling the given list: ['kumar', 2, 3.5, 'include', 1, 'help', 5, 'Bipin']

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.