Open In App

Generating random number list in Python

Last Updated : 18 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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]

Random Number Using Numpy

The random function provided by the Numpy module can be more useful for you as it provides little better functionality and performance as compared to the random module.

Method 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.

Python3




# importing numpy module
import numpy as np
 
# print the list of 10 integers from 3  to 7
print(list(np.random.randint(low = 3,high=8,size=10)))
 
# print the list of 5 integers from 0 to 2
# if high parameter is not passed during
# function call then results are from [0, low)
print(list(np.random.randint(low = 3,size=5)))


Output: 
[5, 3, 6, 7, 4, 5, 7, 7, 7, 7]
[0, 2, 1, 2, 1]

Method 2. Generating a 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).

Python3




import numpy as np
 
# generates list of 4 float values
print(np.random.random_sample(size = 4))
 
# generates 2d list of 4*4
print(np.random.random_sample(size = (4,4)))


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 a few extra probability distributions which can help in scientific research.



Similar Reads

Generating random Id's in Python
In python there are different ways to generate id's. Let's see how different types of Id's can be generated using python without using inbuilt Python libraries. 1. Generating Random Integer as Ids' Code #1 : Print 10 random values of numbers between 1 and 100. C/C++ Code # Python3 code to demonstrate the # random generation of Integer id's import r
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness
3 min read
Generating random strings until a given string is generated
Given the string, the task is to generate the same string using the random combination of special character, numbers, and alphabets. Examples : Input : GFG Output :n4W mK7 k1x q;;, !g . . . . . GF, GFf GFp GFG Target matched after 167 iterations Prerequisite : Generating random Id’s in Python string.ascii_lowercase, string.digits, string.ascii_uppe
2 min read
Generating Random Integers in Pandas Dataframe
Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code that is purely written in C or Python. Here we will see how to generate random integers in the Pandas datagram. We will be using the numpy.random.randint() method to generate random integers. Generating Random
3 min read
Generating a Set of Tuples from a List of Tuples in Python
Python provides a versatile set of tools for manipulating data structures, and when it comes to working with tuples, developers often need to extract unique elements or create a set of tuples from a given list. In this article, we will explore some simple and commonly used methods to generate a set of tuples from a list of tuples in Python. Generat
4 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
Generating Word Cloud in Python
Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites. For generating word cloud in Python, modules needed are
2 min read
Generating Word Cloud in Python | Set 2
Prerequisite: Generating Word Cloud in Python | Set - 1Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.F
5 min read
Practice Tags :