Python Generate random numbers within a given range and store in a list

PythonServer Side ProgrammingProgramming

In this article we will see how to generate Random numbers between a pair of numbers and finally store those values into list.

We use a function called randint. First let's have a look at its syntax.


randint(start, end)
Both start and end should be integers.
Start should be less than end.

In this example we use the range function in a for lowith help of append we generate and add these random numbers to the new empty list.


 Live Demo

import random
def randinrange(start, end, n):
   res = []
   for j in range(n):
      res.append(random.randint(start, end))
   return res
# Number of random numbers needed
n = 5
# Start value
start = 12
#End value
end = 23
print(randinrange(start, end, n))


Running the above code gives us the following result −

[21, 20, 20, 17, 20]
Updated on 09-Jul-2020 13:39:55