Open In App

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

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given lower and upper limits, Generate random numbers list in Python within a given range, starting from ‘start’ to ‘end’, and store them in the list. Here, we will generate any random number in Python using different methods.

Examples:

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

Input: num = 5, start = 10, end = 15
Output: [15, 11, 15, 12, 11]
Explanation: The output contains 5 random numbers in range [10, 15]

Method 1: Generate random integers using random.randrange() method

Python provides a function named randrange() in the random package that can produce random numbers from a given range while still enabling spaces for steps to be included. The below example uses randrange() to randomly print integers.

Python3




import random
 
 
print("Random integers between 0 and 9: ")
for i in range(4, 15):
     y = random.randrange(9)
     print(y)


Output:

Random integers between 0 and 9: 
4
7
2
8
4
6
2
3
1
5
3

Method 2: Generate random integers using random.uniform() method

In python, there’s an inbuilt method, “random.uniform()” which performs this task with ease and uses just one word. This method is defined in the “random” module. It Returns the generated floating-point random number between the lower limit and upper limit. 

Python3




import random
 
 
print("Random integers between 0 and 9: ")
for i in range(4, 11):
     y = random.uniform(4, 10)
     print(y)


Output:

Random integers between 0 and 9: 
7.157267168334274
7.924883261968617
5.353672487638509
9.769791404923588
5.511960438487713
8.116097767143245
7.5873695577485165

Method 3: Generate random integers using randbelow() method

For handling crucial information including cryptographically secure passwords, account authentication, security tokens, and related secrets, the secrets module is utilized to generate random integers. We can use randbelow() function from the secrets module to generate random integers. The below example uses randbelow() to randomly print integers.

Python3




from secrets import randbelow
 
for _ in range(3, 9):
 
    print(randbelow(15))


Output:

14
7
13
10
9
7

Method 4: Generate random integers using the random.randint() method

Python provides a random module to generate random numbers. To generate random numbers we have used the random function along with the use of the random.randint function. randint accepts two parameters, a starting point, and an ending point. Both should be integers and the first value should always be less than the second.

Python3




# Python code to generate
# random numbers and
# append them to a list
import random
 
# Function to generate
# and append them
# start = starting range,
# end = ending range
# num = number of
# elements needs to be appended
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]

Method 5:  Using the NumPy random.randint() method to generate random numbers

The random module in Python 3 includes a built-in function called randint() in Python. The random module provides access to many useful functions, one of which is randint, which can produce random numbers.  The below example uses randint() to randomly print integers.

Python3




# Python code to generate
# random numbers and
# append them to a list
import numpy as np
def Rand(start, end, num):
    res = []
 
    for j in range(num):
        res.append(np.random.randint(start, end))
 
    return res
 
 
# Driver Code
num = 10
start = 20
end = 40
print(Rand(start, end, num))


Output:

[30, 30, 38, 39, 39, 37, 24, 25, 28, 32]

Using random.sample() function:

Approach:

The easiest and most efficient way to generate random numbers within a given range and store them in a list is to use the random.sample() function. Here’s the algorithm for generating random numbers within a given range and storing them in a list using the random.sample() function:

Import the random module.
Use the random.sample() function to generate a list of unique random numbers within the given range.
 

Python3




import random
 
num = 10
start = 20
end = 40
 
result = random.sample(range(start, end + 1), num)
 
print(result)


Output

[26, 33, 21, 40, 23, 39, 34, 38, 36, 32]

Time Complexity: O(n)
Auxiliary Space: O(n)

Using Numpy:

Algorithm:

  1. Import the numpy module and functools module.
  2. Define a function Rand() which takes three arguments as input, start, end, and num.
  3. Create an empty list ‘res’ and iterate num times using a for loop.
  4. In each iteration, append a randomly generated integer between the start and end range using the numpy module.
  5. Return the res list.
  6. Define the values of num, start, and end.
  7. Use reduce() function to generate the list of random numbers.
  8. Define a lambda function which takes two arguments, acc and x.
  9. In each iteration of reduce(), append a randomly generated integer between the start and end range using the numpy module.
  10. The reduce() function will iterate num times and return the final list of random numbers.
  11. Print the final result.

Python3




from functools import reduce
import numpy as np
 
num = 10
start = 20
end = 40
 
result = reduce(lambda acc, x: acc + [np.random.randint(start, end)], range(num), [])
 
print(result)
#This code is contributed by Rayudu.


Output:

[27, 36, 21, 24, 34, 29, 31, 31, 22, 33]

Time Complexity: O(n), where n is the value of num.
Space Complexity: O(n), as we are storing n random numbers in the list.



Similar Reads

Python | Numbers in a list within a given range
Given a list, print the number of numbers in the given range. Examples: Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4 Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter
6 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is updated with 9 from 4th to 8th index. Input : test_
3 min read
GUI to generate and store passwords in SQLite using Python
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We
8 min read
How to generate random numbers from a log-normal distribution in Python ?
A continuous probability distribution of a random variable whose logarithm is usually distributed is known as a log-normal (or lognormal) distribution in probability theory. A variable x is said to follow a log-normal distribution if and only if the log(x) follows a normal distribution. The PDF is defined as follows. Where mu is the population mean
3 min read
Python - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed. Method #1: Using choice() + list comprehen
3 min read
Python | Generate random number except K in list
Sometimes, while working with Python, we can have a problem in which we need to generate random numbers. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random numbers from a list except K. Let's discuss certain ways in which this task can be performed. Method #1 : Using choice() + list compr
6 min read
Generate random numbers and background colour in Django
In this article, we will learn how to generate random numbers and background colors in Python Django. And we will also see different steps related to a random number in Django. These are the following steps that we are going to discuss in this tutorial: What is the Django?Functions to generate a random numberFunctions to generate random background
4 min read
Python | Generate random string of given length
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let's discuss certain ways in which this can be performed in Python. Here, we will use Random string ge
3 min read
Generate five random numbers from the normal distribution using NumPy
In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distrib
2 min read
Generate Random Numbers From The Uniform Distribution using NumPy
Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. Syntax: numpy.random.uniform(low = 0.0, high = 1.0, size = None
1 min read
Practice Tags :