Generate random numbers between specific range in Python
This post will discuss how to generate n random numbers between the specified range in Python.
1. Using random.randint() function
The random.randint(x, y) function generates the random integer n such that x <= n <= y. You can use it as following to generate random numbers between a certain range:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import random if __name__ == '__main__': start = 2 # inclusive end = 5 # inclusive n = 10 # size x = [random.randint(start, end) for _ in range(n)] print(x) |
2. Using random.randrange() function
If you need to generate a random number exclusive of the end argument (i.e., x <= n < y), consider using the random.randrange(x, y) function. In other words, random.randrange(x, y+1) is same as the random.randint(x, y).
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import random if __name__ == '__main__': start = 2 # inclusive end = 5 # exclusive n = 10 # size x = [random.randrange(start, end) for _ in range(n)] print(x) |
3. Using random.choices() function
Another plausible way to generate random numbers from a continuous sequence is using the random.choice() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import random if __name__ == '__main__': start = 2 # inclusive end = 5 # exclusive n = 10 # size x = random.choices(range(start, end), k=n) print(x) |
4. Using Numpy
If you prefer Numpy, you can try numpy.random.randint() or numpy.random.uniform() function.
⮚ numpy.random.randint
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np if __name__ == '__main__': start = 2 # inclusive end = 5 # exclusive n = 10 # size x = np.random.randint(low=start, high=end, size=(n)) print(x) |
⮚ numpy.random.uniform
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np if __name__ == '__main__': start = 2 # inclusive end = 5 # exclusive n = 10 x = np.random.uniform(low=start, high=end, size=(n)).astype(int) print(x) |
That’s all about generating random numbers between specified ranges in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)