Examples of how to create a list of random integers in python:
Using the function randint
The python function randint can be used to generate a random integer in a chosen interval [a,b]:
>>> import random
>>> random.randint(0,10)
7
>>> random.randint(0,10)
0
A list of random numbers can be then created using python list comprehension approach:
>>> l = [random.randint(0,10) for i in range(5)]
>>> l
[4, 9, 8, 4, 5]
Using the function randrange
Another solution is to use randrange function (except that can specify a step if you need):
>>> l = [random.randrange(0,10) for i in range(5)]
>>> l
[1, 7, 4, 3, 1]
>>> l = [random.randrange(0,10,2) for i in range(5)]
>>> l
[2, 4, 4, 6, 0]
Using the function sample
To create a list of random numbers with no repetition, a solution is to use random.sample function
>>> l = random.sample(range(1,100), 10)
>>> l
[89, 56, 87, 51, 46, 25, 52, 44, 10, 32]
References
Links | Site |
---|---|
Random Numbers | pythonprogramminglanguage |
module-random | python doc |
random.sample | python doc |
Generate 'n' unique random numbers within a range | stackoverflow |
Generating a list of random integers in python 3 | stackoverflow |
Create a list of random numbers | stackoverflow |