Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Generate random numbers within a given range and store in a list
In this article we will see how to generate random numbers between a pair of numbers and store those values in a list. Python's random module provides the randint() function for this purpose.
Syntax
random.randint(start, end)
Parameters:
-
start? Lower bound (inclusive) -
end? Upper bound (inclusive) - Both start and end should be integers
- Start should be less than or equal to end
Using a Function with Loop
In this example we use the range() function in a for loop. With help of append() we generate and add these random numbers to a new empty list ?
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]
Using List Comprehension
A more concise approach using list comprehension ?
import random
def generate_random_list(start, end, n):
return [random.randint(start, end) for _ in range(n)]
# Generate 7 random numbers between 1 and 10
numbers = generate_random_list(1, 10, 7)
print(numbers)
[3, 8, 1, 9, 5, 2, 7]
Using random.choices()
For generating multiple random numbers with replacement, you can use random.choices() ?
import random # Generate 6 random numbers between 5 and 15 start, end = 5, 15 count = 6 numbers = random.choices(range(start, end + 1), k=count) print(numbers)
[12, 8, 15, 11, 7, 9]
Comparison
| Method | Syntax Complexity | Best For |
|---|---|---|
randint() with loop |
Medium | Custom logic needed |
| List comprehension | Low | Simple, readable code |
choices() |
Low | Large ranges efficiently |
Conclusion
Use list comprehension with randint() for simple random number generation. For large ranges or weighted selection, consider random.choices().
Advertisements
