- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- C/C++ Program for nth Catalan Number?
- C Program to Check if all digits of a number divide it
- Concatenate a string given number of times in C++ programming
- Superperfect Number in C programming
- sibling of a list element in JavaScript?
- Sum of the nodes of a Singly Linked List in C Program
- HTML DOM Input Number value Property
- HTML DOM Input Number type Property
- How to find the number of days in a month of a particular year in Java?
- number of elements a particular tag contains in JavaScript?
- Print multiples of Unit Digit of Given Number in C Program
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- C++ Programming for Smallest K digit number divisible by X?
- To find sum of even factors of a number in C++ Program?

There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers.

The random() method in random module generates a float number between 0 and 1.

import random n = random.random() print(n)

Running the above code gives us the following result −

0.2112200

The randint() method generates a integer between a given range of numbers.

import random n = random.randint(0,22) print(n)

Running the above code gives us the following result −

2

We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one.

import random randomlist = [] for i in range(0,5): n = random.randint(1,30) randomlist.append(n) print(randomlist)

Running the above code gives us the following result −

[10, 5, 21, 1, 17]

We can also use the sample() method available in random module to directly generate a list of random numbers.Here we specify a range and give how many random numbers we need to generate.

import random #Generate 5 random numbers between 10 and 30 randomlist = random.sample(range(10, 30), 5) print(randomlist)

Running the above code gives us the following result −

[16, 19, 13, 18, 15]

Advertisements