Random Number Using random module
Python Random module is an in-built module of Python which is used to generate random numbers. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc.
Method 1: Using the random.randint()
By using random.randint() we can add random numbers into a list.
Python3
import random rand_list = [] n = 10 for i in range (n): rand_list.append(random.randint( 3 , 9 )) print (rand_list) |
Output
[9, 3, 3, 6, 8, 5, 4, 6, 3, 7]
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.
Python3
# Python3 code to demonstrate # to generate random number list # using random.sample() import random # using random.sample() # to generate random number list res = random.sample( range ( 1 , 50 ), 7 ) # printing result print ( "Random number list is : " + str (res)) |
Output
Random number list is : [49, 20, 23, 34, 6, 29, 35]
Method 3: Using list comprehension + randrange()
The naive method to perform this particular task can be shortened using list comprehension. randrange function is used to perform the task of generating the random numbers.
Python3
# Python3 code to demonstrate # to generate random number list # using list comprehension + randrange() import random # using list comprehension + randrange() # to generate random number list res = [random.randrange( 1 , 50 , 1 ) for i in range ( 7 )] # printing result print ( "Random number list is : " + str (res)) |
Output
Random number list is : [32, 16, 9, 28, 19, 31, 21]
Method 4: using loop + randint()
Python3
# Method 3: For Loop Random Int List [0, 51] import random lis = [] for _ in range ( 10 ): lis.append(random.randint( 0 , 51 )) print (lis) |
Output:
[3, 11, 48, 2, 48, 2, 8, 51, 8, 5]
Generating random number list in Python
Sometimes, in making programs for gaming or gambling, we come across the task of creating a list all with random numbers in Python. 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 the most concise manner. Let’s discuss certain ways in which this can be done.