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
Generating random number list in Python
There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers.
Generating a Single Random Number
The random() method in random module generates a float number between 0 and 1.
Example
import random n = random.random() print(n)
Output
Running the above code gives us the following result ?
0.2112200
Generating Number in a Range
The randint() method generates an integer between a given range of numbers (inclusive).
Example
import random n = random.randint(0, 22) print(n)
Output
Running the above code gives us the following result ?
2
Using For Loop
We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one.
Example
import random
numbers = []
for i in range(0, 5):
n = random.randint(1, 30)
numbers.append(n)
print(numbers)
Output
Running the above code gives us the following result ?
[10, 5, 21, 1, 17]
Using random.sample()
We can also use the sample() method available in random module to directly generate a list of random numbers. Here we specify a range and give how many random numbers we need to generate. Note that sample() generates unique numbers without replacement.
Example
import random # Generate 5 random numbers between 10 and 30 numbers = random.sample(range(10, 30), 5) print(numbers)
Output
Running the above code gives us the following result ?
[16, 19, 13, 18, 15]
Using List Comprehension
A more Pythonic way to generate random number lists is using list comprehension with randint().
Example
import random # Generate 5 random numbers between 1 and 100 numbers = [random.randint(1, 100) for _ in range(5)] print(numbers)
Output
Running the above code gives us the following result ?
[45, 23, 78, 12, 56]
Comparison of Methods
| Method | Allows Duplicates? | Best For |
|---|---|---|
| For loop | Yes | Simple implementation |
| random.sample() | No | Unique numbers only |
| List comprehension | Yes | Concise Pythonic code |
Conclusion
Use random.sample() for unique numbers, list comprehension for concise syntax, or for loops for step-by-step control. Choose the method based on whether you need duplicates and your coding style preference.
