Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, generate a given count of random numbers within a given range, starting from ‘start’ to ‘end’ and store them in list.
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 to generate random numbers. To generate random numbers we have used the random function along with the use of the randint function.
Syntax:
randint(start, end)
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.
# 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 = 10start = 20end = 40print(Rand(start, end, num)) |
Output:
[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
Recommended Posts:
- Secrets | Python module to Generate secure random numbers
- Python | Numbers in a list within a given range
- Python | Select random value from a list
- Generating random number list in Python
- Random Numbers in Python
- Python | Generate successive element difference list
- range() to a list in Python
- Python List Comprehension | Three way partitioning of an array around a given range
- Python | Print list elements in circular range
- Python program to print all even numbers in a range
- Python program to print all odd numbers in a range
- Python program to print all positive numbers in a range
- Python program to print all negative numbers in a range
- Python program to count Even and Odd numbers in a List
- Python program to print odd numbers in a List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



