How to Generate Random Integers in Range in Python
Python is a popular programming language when working with math and data because of how easy it is to work with numbers.
A popular operation in Python is to generate random numbers in a specific range so that you can use it in your code.
In this post, we'll learn how to generate random numbers in a specific range in Python.
Using random.randint()
A simple way to generate random numbers in a specific range is to use the randint()
function.
This function comes from the random
module and you can use it by just importing it.
Let's look at how to generate a random number between 0 and 10 in Python:
PYTHONimport random
number = random.randint(0, 10)
print(number)
BASH5
Keep in mind that this will include the number 0
but exclude the number 10
.
Now, if you want to generate a list of these numbers, you can use the range()
function:
PYTHONimport random
numbers = [random.randint(0, 10) for p in range(0, 10)]
print(numbers)
BASH[1, 8, 4, 0, 5, 9, 2, 3, 6, 8]
Here is the general syntax:
PYTHONimport random
range_start = 0
range_end = 10
gen_count = 10
numbers = [random.randint(range_start, range_end) for p in range(0, gen_count)]
print(numbers)
Using random.randrange()
Another function that comes with the random
module is randrange()
.
This function also requires a start and end range, however, it also allows you to specify a step size.
The step
parameter is optional, but if you don't specify it, it will default to 1
.
This parameter controls the step size of the range, so if you want to generate a list of numbers between 0 and 10, but only in steps of 2, you can use the following syntax:
PYTHONimport random
numbers = [random.randrange(0, 10, 2) for p in range(0, 10)]
print(numbers)
BASH[4, 2, 6, 2, 4, 8, 6, 4, 2, 2]
Using random.sample()
When you want to ensure that you have a random list of unique numbers, you can use the sample()
function.
This function will generate a random list of integers for you while ensuring they are all unique.
Let's see how it works:
PYTHONimport random
numbers = random.sample(range(0, 10), 10)
print(numbers)
BASH[4, 3, 8, 1, 7, 2, 9, 6, 0, 5]
Conclusion
In this post, we learned how to generate random numbers in a specific range in Python.
Python has several built-in functions that you can use to generate the random numbers that you need. Simply pick the one that is right for your use-case.
Thanks for reading and happy coding!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase