Open In App

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

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to generate random numbers within a given range and store them in a list in Python. For example, you might want to generate 5 random numbers between 20 and 40 and store them in a list, which could look like this: [30, 34, 31, 36, 30]. Let's explore different methods to do this efficiently.

Using random.choices()

random.choices() function is an efficient way to randomly select multiple values with replacement from a given range. It's ideal when you want fast and simple random number generation without needing loops.

Python
import random

no = 10
a = 20 # start
b = 40 # end

res = random.choices(range(a, b + 1), k=no)
print(res)

Output
[22, 32, 36, 23, 39, 25, 35, 38, 37, 25]

Explanation: range(a, b + 1) creates a sequence of numbers from 20 to 40 and the parameter k=no specifies that 10 random numbers should be selected from that sequence.

Using random.randint()

random.randint(), which generates a random integer between two values, inclusive. By combining it with a list comprehension, you create a compact and readable one-liner that repeats the operation no times.

Python
import random

no = 10
a = 50 # start
b = 90 # end

res = [random.randint(a,b ) for _ in range(no)]
print(res)

Output
[64, 87, 52, 56, 81, 51, 58, 79, 52, 59]

Explanation: List comprehension runs random.randint(a, b) ten times to generate random integers between 50 and 90, storing the results in the list res.

Using numpy's random.randint()

NumPy is a powerful numerical computing library and its random.randint() function is optimized for generating large arrays of random integers very quickly. You specify the start, end and how many numbers you want. Then convert it to a list using .tolist().

Python
import numpy as np

no = 10
a = 10 # start
b = 40 # end

res = np.random.randint(a, b + 1, size=no).tolist()
print(res)

Output
[24, 26, 25, 10, 38, 40, 14, 10, 37, 20]

Explanation: randint() quickly generates 10 random numbers between 10 and 40 in one go. The size=no tells it how many to create and .tolist() simply turns the result into a regular Python list.

Using map()

This approach applies the random.randint() function over a range using Python’s built-in map() function. It uses a lambda function to repeat the call no times. It performs similarly to list comprehension, but uses a functional programming style.

Python
import random

no = 10
a = 70 # start
b = 90 # end

res = list(map(lambda _: random.randint(a,b), range(no)))
print(res)

Output
[85, 82, 89, 89, 83, 82, 85, 74, 74, 82]

Explanation: map() with a lambda function to generate 10 random integers between 70 and 90. It applies random.randint(a, b) for each item in range(no), and list() collects the results into a list named res.


Next Article
Practice Tags :

Similar Reads