Here are 2 ways to generate random numbers in a Python list:
(1) Generate random numbers that cannot be repeated:
import random
my_list = random.sample(range(lowest number, highest number), number of items in the list)
print(my_list)
For example, let’s generate 15 random numbers, where the lowest number is 1 (inclusive), while the highest number is 30 (exclusive):
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, which cannot be repeated:
[6, 16, 3, 5, 22, 24, 1, 7, 11, 4, 29, 13, 17, 28, 25]
(1) Generate random numbers that can be repeated:
import numpy as np
data = np.random.randint(1, 30, size=15)
my_list = data.tolist()
print(my_list)
As can be observed, 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]
Note that: