
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Generating random number list in Python
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.
Generating a Single Random Number
The random() method in random module generates a float number between 0 and 1.
Example
import random n = random.random() print(n)
Output
Running the above code gives us the following result −
0.2112200
Generating Number in a Range
The randint() method generates a integer between a given range of numbers.
Example
import random n = random.randint(0,22) print(n)
Output
Running the above code gives us the following result −
2
Generating a List of numbers Using For Loop
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.
Example
import random randomlist = [] for i in range(0,5): n = random.randint(1,30) randomlist.append(n) print(randomlist)
Output
Running the above code gives us the following result −
[10, 5, 21, 1, 17]
Using random.sample()
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.
Example
import random #Generate 5 random numbers between 10 and 30 randomlist = random.sample(range(10, 30), 5) print(randomlist)
Output
Running the above code gives us the following result −
[16, 19, 13, 18, 15]
- Related Articles
- Generating random Id’s in Python
- Generating Random Prime Number in JavaScript
- Generating random number in a range in C
- Generating Random id's using UUID in Python
- Generating random numbers in C#
- Generating random numbers in Java
- Generating a random number that is divisible by n in JavaScript
- Generating random hex color in JavaScript
- Generating Random Short Id in Node.js
- Generating Random String Using PHP
- Generating random strings until a given string is generated using Python
- How to pick a random number not in a list in Python?
- Generating random string of specified length in JavaScript
- Python – Random range in a List
- Random Number Functions in Python
