Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers. This task is to perform in general using loop and appending the random numbers one by one. But there is always a requirement to perform this in most concise manner. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + randrange()
The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers.
Random number list is : [21, 27, 23, 20, 21, 25, 15]
Method #2 : Using random.sample()
This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list.
Random number list is : [8, 46, 45, 49, 15, 6, 31]
Method #3: Using numpy.random
The random function provided by the numpy module can be more useful for you as it provides little better functionality and performance as compare to the random module.
1. Generating a list of random integers using numpy.random.randint function
This function returns random integers from the “discrete uniform” distribution of the integer data type.
Output: [5, 3, 6, 7, 4, 5, 7, 7, 7, 7] [0, 2, 1, 2, 1]
2. Generating list of random floating values using numpy.random.random_sample function
This function return random float values in half open interval [0.0, 1.0).
output: [0.08035145 0.94966245 0.92860366 0.22102797] [[0.02937499 0.50073572 0.58278742 0.02577903] [0.37892104 0.60267882 0.33774815 0.28425059] [0.57086088 0.07445422 0.86236614 0.33505317] [0.83514508 0.82818536 0.1917555 0.76293027]]
The benefit of using numpy.random over the random module of python is that it provides few extra probability distributions which can help in scientific research.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course