Python | Generating random numbers in a given range and saving in a list

Python Methods and Functions

Examples:

 Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] The output contains 10 random numbers in range [20, 40]. Input: num = 5, start = 10, end = 15 Output: [15, 11, 15, 12, 11] The output contains 5 random numbers in range [10, 15]. 

Python provides a random module for generating random numbers. We used the random function along with the randint function to generate random numbers. 
Syntax :

 randint (start, end) 

randint takes two parameters: a start point and an end point. Both must be integers and the first value must always be less than the second.

# Python code to generate
# random numbers and
# add them to the list

import random

 
# Function to generate
# and add them
# start = starting range,
# end = end range
# number = amount
# elements must be added

def Rand (start, end, num):

res = []

  

  for j in range (num):

res.append (random.randint (start, end))

 

return res

  
Driver code

num = 10

start = 20

end = 40

print (Rand (start, end, num))

Output:

 [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] 




Tutorials