Skip to content
Home » Generate Random Number in Python

Generate Random Number in Python

Generating a Random Number

The random() method in the random module returns a float number between 0 and 1.

import random  
num = random.random()  
print(num)  

Output:

0.6425903878097966

Generate Random Number within a Given Range

The randint() function in the Python random module creates an integer number within a given range. The two numbers that define the range can be given as arguments.

import random  
num = random.randint(20,100)  
print(num)  

Output:

46

Generating a list of random numbers using for loop

To generate a list of random numbers, use the randint() function with the for loop. To accomplish so, we must first establish an empty list, and then append the generated random numbers one by one to the empty list.

import random  
random_lst = []  
for i in range(0,10):  
    num = random.randint(1,50)  
    random_lst.append(num)  
print(random_lst)  

Output:

[50, 39, 41, 33, 38, 36, 28, 11, 36, 3]

Using random.sample()

The random module also includes the sample() method, which generates a list of random numbers directly. The sample() method is used to generate random numbers, as shown below.

import random   
rand_lst = random.sample(range(40, 90), 7)  
print(rand_lst)  

Output:

[84, 52, 71, 58, 54, 49, 40]

Also Read:

Program to Check Given number is a Prime Number