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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- How To Create a Modal Popup Box with CSS and JavaScript