Getting random integers in Python
# import the function from random import randint # set your parameters howmany = 10 min = 0 max = 100 # use a list comprehension to fill an array rand_ints = [randint(min,max) for _ in range(howmany)]
Seems kinds of bulky, but you specify how many numbers you would like, what range to draw them from, and then call the radint() function over and over again until you have the numbers you need, using a for loop with a throaway variable “_”.
But there’s a few ways to do this! If you have NumPy installed, it has a similar function for generating random integers, and the lines of code above, can be reduced to just two: import the library, call the function.
from numpy.random import randint randint(0,100,10)
The result is as follows:
array([42, 99, 30, 94, 60, 90, 7, 31, 91, 11])
Both of these methods would usually be preceded by a call to “seed” the random number generator, so that you can set a reproducible starting point for random number generation. The function has the same name in each library, and calling seed for one does not set the seed for the other. But that’s more than you need to know for now.