Python – Random range in a List

PythonServer Side ProgrammingProgramming

When it is required to find the random range in a list, a list comprehension and the ‘randrange’ method present in ‘random’ package is used.

Example

Below is a demonstration of the same −

import random

my_result = [random.randrange(1, 100, 1) for i in range(10)]

print ("The result is :")
print(my_result)

Output

The result is :
[40, 73, 58, 45, 68, 19, 86, 6, 15, 71]

Explanation

  • The required packages are imported into the environment.

  • A list comprehension is used to iterate over the list, and 'randrange' method is used to generate random number in the given range.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 10:21:24
Advertisements