You may use the following template in order to generate random numbers in a Python list (under Python 3):
import random my_list = random.sample(range(lowest number, highest number), number of items in the list) print(my_list)
Few things to keep in mind:
- The lowest number may be included in the list, but the highest number will be excluded
- The same number cannot be repeated twice in the list
- The range must be equal or greater than the number of items in the list (otherwise, you’ll get the following ValueError: Sample larger than population or is negative)
Example of Generating Random Numbers in a Python List
To start with a simple example, let’s create a list with 15 random numbers, where:
- The lowest number is 1 (inclusive)
- The highest number is 30 (exclusive)
Here is the code that you may apply in Python:
import random my_list = random.sample(range(1, 30), 15) print(my_list)
As you can see, the number of items (i.e., random numbers in the list) is 15:
[6, 16, 3, 5, 22, 24, 1, 7, 11, 4, 29, 13, 17, 28, 25]
Note that the lowest number specified (‘1′) is included in the list, but the highest number (’30’) is excluded. Also, the same number is not repeated twice within the list.
But what if you want to generate random numbers that can repeat more than once in the list?
In the next section, you’ll see how to accomplish this task.
Generate Random Numbers that may Repeat More Than Once in the List
There are times when you may need to generate a list of random numbers, where each number may potentially appear more than once.
In the code below:
- Numpy was used to generate 15 random numbers from 1 (inclusive) to 30 (exclusive)
- tolist() was used to convert the NumPy array to a list
Here is the complete code:
import numpy as np data = np.random.randint(1,30,size=15) my_list = data.tolist() print(my_list)
As you may observe, a random number may appear more than once in the list (e.g., 18 and 10 below):
[7, 2, 23, 18, 12, 6, 18, 20, 24, 10, 4, 9, 10, 17, 15]