Next Steps
I want to hear from you. What do you think of this article on
randint()
and
randrange()
? Or maybe I missed one of the usages of those two functions. Either way, let me know by leaving a comment below.
Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.
- Python random data generation Exercise to practice and master the random data generation techniques in Python.
- Python random data generation Quiz to test your random data generation concepts.
Notes on Reproducibility¶
Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By reusing a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.
Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:
-
If a new seeding method is added, then a backward compatible seeder will be offered.
-
The generator’s
random()
method will continue to produce the same sequence when the compatible seeder is given the same seed.
All contributors
- Anonymous contributorAnonymous contributor3071 total contributions
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor186 total contributions
- BrandonDusch580 total contributions
- Anonymous contributor
- christian.dinh
- Anonymous contributor
- BrandonDusch
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Generate a secure random integer
Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number simultaneously.
If you are producing random numbers for a security-sensitive application, then you must use this approach.
Use the secrets module if you are using a Python version higher than 3.6.
import secrets # secure random integer # from 0 to 10 secure_num = secrets.randbelow(10) print(secure_num) # Output 5
If you are using Python version less than 3.6, then use the
random.SystemRandom().randint()
or
random.SystemRandom().randrange()
functions.
Discrete distributions¶
The following function generates a discrete distribution.
- random.binomialvariate(n=1, p=0.5)¶
-
Binomial distribution. Return the number of successes for n independent trials with the probability of success in each trial being p:
Mathematically equivalent to:
sum(random() < p for i in range(n))
The number of trials n should be a non-negative integer. The probability of success p should be between
0.0 <= p <= 1.0
. The result is an integer in the range
0 <= X <= n
.New in version 3.12.
Functions for sequences¶
- random.choice(seq)¶
-
Return a random element from the non-empty sequence seq. If seq is empty, raises
IndexError
.
- random.choices(population, weights=None, *, cum_weights=None, k=1)¶
-
Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises
IndexError
.If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using
itertools.accumulate()
). For example, the relative weights
[10, 5, 30, 5]
are equivalent to the cumulative weights
[10, 15, 45, 50]
. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a
TypeError
to specify both weights and cum_weights.The weights or cum_weights can use any numeric type that interoperates with the
float
values returned by
random()
(that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A
ValueError
is raised if all weights are zero.For a given seed, the
choices()
function with equal weighting typically produces a different sequence than repeated calls to
choice()
. The algorithm used by
choices()
uses floating point arithmetic for internal consistency and speed. The algorithm used by
choice()
defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.New in version 3.6.
Changed in version 3.9: Raises a
ValueError
if all weights are zero.
- random.shuffle(x)¶
-
Shuffle the sequence x in place.
To shuffle an immutable sequence and return a new shuffled list, use
sample(x, k=len(x))
instead.Note that even for small
len(x)
, the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.Changed in version 3.11: Removed the optional parameter random.
- random.sample(population, k, *, counts=None)¶
-
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. For example,
sample(['red', 'blue'], counts=[4, 2], k=5)
is equivalent to
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
.To choose a sample from a range of integers, use a
range()
object as an argument. This is especially fast and space efficient for sampling from a large population:
sample(range(10000000), k=60)
.If the sample size is larger than the population size, a
ValueError
is raised.Changed in version 3.9: Added the counts parameter.
Changed in version 3.11: The population must be a sequence. Automatic conversion of sets to lists is no longer supported.
Parameters of randrange Python Function
Start, Stop, and Width are the three input parameters for the random.randrange() function. The two parameters start and width are the only two of these three that can be ignored. These 3 parameters are explained below.
- A starting or lower limit number in a random range serves as the start parameter. Start takes the default value of 0 if it is not passed in as a parameter.
- The last or highest number in a random range is referred to as a stop parameter.
- A range between each number in the random sequence makes up the width parameter. If the width parameter is not provided, this optional parameter takes the default value of 1.
The end parameter is not used when the random integer number is generated by the randrange(start, stop, width) function. The stop parameter is excluded and is not produced by a random number generator.
Recipes¶
These recipes show how to efficiently make random selections
from the combinatoric iterators in the
itertools
module:
def random_product(*args, repeat=1): “Random selection from itertools.product(*args, **kwds)” pools = [tuple(pool) for pool in args] * repeat return tuple(map(random.choice, pools)) def random_permutation(iterable, r=None): “Random selection from itertools.permutations(iterable, r)” pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) def random_combination(iterable, r): “Random selection from itertools.combinations(iterable, r)” pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(range(n), r)) return tuple(pool[i] for i in indices) def random_combination_with_replacement(iterable, r): “Choose r elements with replacement. Order the result to match the iterable.” # Result will be in set(itertools.combinations_with_replacement(iterable, r)). pool = tuple(iterable) n = len(pool) indices = sorted(random.choices(range(n), k=r)) return tuple(pool[i] for i in indices)
The default
random()
returns multiples of 2⁻⁵³ in the range
0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactly
representable as Python floats. However, many other representable
floats in that interval are not possible selections. For example,
0.05954861408025609
isn’t an integer multiple of 2⁻⁵³.
The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. The exponent comes from a geometric distribution where exponents smaller than -53 occur half as often as the next larger exponent.
from random import Random from math import ldexp class FullRandom(Random): def random(self): mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) exponent = -53 x = 0 while not x: x = self.getrandbits(32) exponent += x.bit_length() – 32 return ldexp(mantissa, exponent)
All real valued distributions in the class will use the new method:
>>> fr = FullRandom() >>> fr.random() 0.05954861408025609 >>> fr.expovariate(0.25) 8.87925541791544
The recipe is conceptually equivalent to an algorithm that chooses from
all the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. All such
numbers are evenly spaced, but most have to be rounded down to the
nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest
positive unnormalized float and is equal to
math.ulp(0.0)
.)
See also
Generating Pseudo-random Floating-Point Values a
paper by Allen B. Downey describing ways to generate more
fine-grained floats than normally generated by
random()
.
Hàm randrange() trong Python trả về một phần tử được lựa chọn một cách ngẫu nhiên từ dãy (start, stop, step).
Nội dung chính
Python3
|
Output :
Random number from 14.5-100 is :
Runtime Error :
Traceback (most recent call last):
File “/home/5e40f42505a6926d0c75a09bec1279d9.py”, line 9, in
print (random.randrange(14.5,100))
File “/usr/lib/python3.5/random.py”, line 182, in randrange
raise ValueError(“non-integer arg 1 for randrange()”)
ValueError: non-integer arg 1 for randrange()
2. Value Error – start >= stop
Output :
Random number from 500-100 is :
Runtime Error :
Traceback (most recent call last):
File “/home/ea327cf3f1dd801a66a185d101c5cb13.py”, line 9, in
print (random.randrange(500,100))
File “/usr/lib/python3.5/random.py”, line 196, in randrange
raise ValueError(“empty range for randrange() (%d,%d, %d)” % (istart, istop, width))
ValueError: empty range for randrange() (500,100, -400)
Practical Application
Generating random numbers has always been an important application and has been used in many casino games, for gambling for many kid games like ludo, etc which use the concept of Dice. A short game, on who reaches 100 first wins have been depicted in the code below. Each player is allowed a dice of 1-10 numbers, i.e at each turn 1-10 can be attained..
Points to remember about randint() and randrange()
-
Use
randint()
when you want to generate a random number from an inclusive range. -
Use
randrange()
when you want to generate a random number within a range by specifying the increment. It produces a random number from an exclusive range.
You should be aware of some value constraints of a
randrange()
function.
-
The
randint(
) rand
randrange()
works only with integers. You cannot use float numbers. -
The step must not be 0. If it is set to 0, you will get a
ValueError: zero step for randrange()
- The start should not be greater than stop if you are using all positive numbers. If you set start greater than stop, you will get a ValueError: empty range for randrange()
Examples
import random # ValueError: empty range for randrange() print(random.randrange(100, 10, 2))
But, you can also set a start value greater than stop if you are using a negative step value.
import random print(random.randrange(100, 10, -2)) # output 60
Functions for integers¶
- random.randrange(stop)¶
- random.randrange(start, stop[, step])
-
Return a randomly selected element from
range(start, stop, step)
.This is roughly equivalent to
choice(range(start, stop, step))
but supports arbitrarily large ranges and is optimized for common cases.The positional argument pattern matches the
range()
function.Keyword arguments should not be used because they can be interpreted in unexpected ways. For example
randrange(start=100)
is interpreted as
randrange(0, 100, 1)
.Changed in version 3.2:
randrange()
is more sophisticated about producing equally distributed values. Formerly it used a style like
int(random()*n)
which could produce slightly uneven distributions.Changed in version 3.12: Automatic conversion of non-integer types is no longer supported. Calls such as
randrange(10.0)
and
randrange(Fraction(10, 1))
now raise a
TypeError
.
- random.randint(a, b)¶
-
Return a random integer N such that
a <= N <= b
. Alias for
randrange(a, b+1)
.
- random.getrandbits(k)¶
-
Returns a non-negative Python integer with k random bits. This method is supplied with the Mersenne Twister generator and some other generators may also provide it as an optional part of the API. When available,
getrandbits()
enables
randrange()
to handle arbitrarily large ranges.Changed in version 3.9: This method now accepts zero for k.
Cú pháp
Cú pháp của randrange() trong Python:
randrange ([start,] stop [,step])
Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import math module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng math.
Chi tiết về tham số:
-
start — Điểm bắt đầu của dãy giá trị. Điểm này nên được bao gồm trong dãy.
-
stop — Điểm kết thúc của dãy giá trị. Điểm này nên được loại trừ khỏi dãy.
-
step — Bước để thêm vào trong một số để quyết định một số ngẫu nhiên.
Chương trình Python ví dụ
Ví dụ sau minh họa cách sử dụng của randrange() trong Python.
import random # Chon mot so ngau nhien tu 100 <= number < 1000 print “randrange(100, 1000, 2) : “, random.randrange(100, 1000, 2) # Chon mot so ngau nhien khac tu 100 <= number < 1000 print “randrange(100, 1000, 3) : “, random.randrange(100, 1000, 3)
Chạy chương trình Python trên sẽ cho kết quả:
randrange(100, 1000, 2) : 976 randrange(100, 1000, 3) : 520
In this lesson, we will see how to use the
randrange()
and
randint()
functions of a Python random module to generate a random integer number.
Using
randrange()
and
randint()
functions of a random module, we can generate a random integer within a range. In this lesson, you’ll learn the following functions to generate random numbers in Python. We will see each one of them with examples.
Function | Description |
Returns any random integer from 0 to 9 | |
Returns a random integer from 0 to 19 | |
Returns a random integer from 2 to 19. | |
Returns any random integer from 100 to 999 with step 3. For example, any number from 100, 103, 106 … 994, 997. | |
Returns a random negative integer between -50 to -6. | |
Returns a list of random numbers | |
Returns a secure random number |
Example
The following example shows the usage of randrange() method.
#!/usr/bin/python import random # Select an even number in 100 <= number < 1000 print “randrange(100, 1000, 2) : “, random.randrange(100, 1000, 2) # Select another number in 100 <= number < 1000 print “randrange(100, 1000, 3) : “, random.randrange(100, 1000, 3)
When we run above program, it produces following result −
randrange(100, 1000, 2) : 976 randrange(100, 1000, 3) : 520
python_numbers.htm
Advertisements
randrange() Python Function
Python3
|
Output:
Random number from 0-100 is : 26
Random number from 50-100 is : 58
Random number from 50-100 skip 5 is : 90
Exceptions
1. Value Error – Floating point value
Examples¶
Basic examples:
>>> random() # Random float: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 3.1800146073117523 >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 5.148957571865031 >>> randrange(10) # Integer from 0 to 9 inclusive 7 >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 26 >>> choice([‘win’, ‘lose’, ‘draw’]) # Single random element from a sequence ‘draw’ >>> deck = ‘ace two three four’.split() >>> shuffle(deck) # Shuffle a list >>> deck [‘four’, ‘two’, ‘ace’, ‘three’] >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement [40, 10, 50, 30]
Simulations:
>>> # Six roulette wheel spins (weighted sampling with replacement) >>> choices([‘red’, ‘black’, ‘green’], [18, 18, 2], k=6) [‘red’, ‘green’, ‘black’, ‘black’, ‘red’, ‘black’] >>> # Deal 20 cards without replacement from a deck >>> # of 52 playing cards, and determine the proportion of cards >>> # with a ten-value: ten, jack, queen, or king. >>> deal = sample([‘tens’, ‘low cards’], counts=[16, 36], k=20) >>> deal.count(‘tens’) / 20 0.15 >>> # Estimate the probability of getting 5 or more heads from 7 spins >>> # of a biased coin that settles on heads 60% of the time. >>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> def trial(): … return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 … >>> sum(trial() for i in range(10_000)) / 10_000 0.7958
Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample:
# https://www.thoughtco.com/example-of-bootstrapping-3126155 from statistics import fmean as mean from random import choices data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] means = sorted(mean(choices(data, k=len(data))) for i in range(100)) print(f’The sample mean of {mean(data):.1f} has a 90% confidence ‘ f’interval from {means[5]:.1f} to {means[94]:.1f}’)
Example of a resampling permutation test to determine the statistical significance or p-value of an observed difference between the effects of a drug versus a placebo:
# Example from “Statistics is Easy” by Dennis Shasha and Manda Wilson from statistics import fmean as mean from random import shuffle drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] observed_diff = mean(drug) – mean(placebo) n = 10_000 count = 0 combined = drug + placebo for i in range(n): shuffle(combined) new_diff = mean(combined[:len(drug)]) – mean(combined[len(drug):]) count += (new_diff >= observed_diff) print(f'{n} label reshufflings produced only {count} instances with a difference’) print(f’at least as extreme as the observed difference of {observed_diff:.1f}.’) print(f’The one-sided p-value of {count / n:.4f} leads us to reject the null’) print(f’hypothesis that there is no difference between the drug and the placebo.’)
Simulation of arrival times and service deliveries for a multiserver queue:
from heapq import heapify, heapreplace from random import expovariate, gauss from statistics import mean, quantiles average_arrival_interval = 5.6 average_service_time = 15.0 stdev_service_time = 3.5 num_servers = 3 waits = [] arrival_time = 0.0 servers = [0.0] * num_servers # time when each server becomes available heapify(servers) for i in range(1_000_000): arrival_time += expovariate(1.0 / average_arrival_interval) next_server_available = servers[0] wait = max(0.0, next_server_available – arrival_time) waits.append(wait) service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) service_completed = arrival_time + wait + service_duration heapreplace(servers, service_completed) print(f’Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}’) print(‘Quartiles:’, [round(q, 1) for q in quantiles(waits)])
See also
Statistics for Hackers a video tutorial by Jake Vanderplas on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.
Economics Simulation a simulation of a marketplace by Peter Norvig that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).
A Concrete Introduction to Probability (using Python) a tutorial by Peter Norvig covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.
How to use random.randint()
Syntax:
random.randint(start, stop)
This function returns a random integer between a given start and stop integer.
Parameters:
It takes two parameters. Both are mandatory.
-
start
: It is the start position of a range. The default value is 0 if not specified. -
stop
: It is the end position of a range.
Return value:
It will generate any random integer number from the inclusive range. The
randint(start, stop)
consider both the start and stop numbers while generating random integers
How to use Python
randint()
and
randrange()
to get random integers
-
Import random module
Use Python’s random module to work with random data generation.
import it using a
import random
statement. -
Use randint() Generate random integer
Use a
random.randint()
function to get a random integer number from the inclusive range. For example,
random.randint(0, 10)
will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10]. -
Use the randrnage() function to generate a random integer within a range
Use a
random.randrange()
function to get a random integer number from the given exclusive range by specifying the increment. For example,
random.randrange(0, 10, 2)
will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
random.randint() example of generating random number
import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84
Note: You cannot use float numbers in
randint()
. It will raise a ValueError (
non-integer stop for randrange()
) if you use non-integer numbers. Please, read how to generate a random float number within a range.
Uses of randrange Python Function
- It has always been essential to generate random numbers in applications since they have several real-time applications in daily life. An OTP (one-time password) is a random number that is generated and sent to a customer to facilitate a secure transaction.
- When playing the game of Ludo, a random dice number is generated as an additional example of generating a randomly selected number.
- In casino games, this random number generator is frequently used.
- In online bike and car racing games, we have given a random number position, this random number generator is used.
Random negative integer
Let’s see how to generate a random negative integer between -60 to -6.
import random singed_int = random.randrange(-60, -6) print(singed_int) # Output -16
Generate random positive or negative integer
import random for i in range(5): print(random.randint(-10, 10), end=' ') # Output 10 -1 5 -10 -7
Randomly generate 1 or -1
import random num = random.choice([-1, 1]) print(num)
Note: we used random.choice() to choose a single number from the list of numbers. Here our list is
[-1, 1]
.
Working of randrange Python Function
Within the start and stop points that are passed to the randrange() function, the random.randrange() function returns a random number. Start, Stop, and Width are the three parameters that the random.randrange() function accepts as input. The two parameters start and width are optional out of these three.
The end parameter is not used when the random integer number is generated by the randrange(start, stop, width) function. The stop parameter is unique and is not produced by a random number generator.
Consider the function random.randrange(2, 20, 2), which will produce any random integer value between 3 and 30 such as 2, 4, 6, 8,… . But when producing a random number, this algorithm never takes 20 into account.
Python3
|
Total score of Player 1 after turn 1 is : 8
Total score of Player 2 after turn 1 is : 4
Total score of Player 1 after turn 2 is : 13
Total score of Player 2 after turn 2 is : 8
Total score of Player 1 after turn 3 is : 22
Total score of Player 2 after turn 3 is : 16
Total score of Player 1 after turn 4 is : 28
Total score of Player 2 after turn 4 is : 22
Total score of Player 1 after turn 5 is : 33
Total score of Player 2 after turn 5 is : 27
Total score of Player 1 after turn 6 is : 35
Total score of Player 2 after turn 6 is : 33
Total score of Player 1 after turn 7 is : 36
Total score of Player 2 after turn 7 is : 42
Total score of Player 1 after turn 8 is : 38
Total score of Player 2 after turn 8 is : 50
Total score of Player 1 after turn 9 is : 45
Total score of Player 2 after turn 9 is : 55
Total score of Player 1 after turn 10 is : 48
Total score of Player 2 after turn 10 is : 61
Total score of Player 1 after turn 11 is : 54
Total score of Player 2 after turn 11 is : 64
Total score of Player 1 after turn 12 is : 57
Total score of Player 2 after turn 12 is : 70
Total score of Player 1 after turn 13 is : 66
Total score of Player 2 after turn 13 is : 73
Total score of Player 1 after turn 14 is : 72
Total score of Player 2 after turn 14 is : 75
Total score of Player 1 after turn 15 is : 79
Total score of Player 2 after turn 15 is : 76
Total score of Player 1 after turn 16 is : 81
Total score of Player 2 after turn 16 is : 77
Total score of Player 1 after turn 17 is : 89
Total score of Player 2 after turn 17 is : 81
Total score of Player 1 after turn 18 is : 95
Total score of Player 2 after turn 18 is : 90
Total score of Player 1 after turn 19 is : 97
Total score of Player 2 after turn 19 is : 99
Total score of Player 1 after turn 20 is : 102
Player 1 wins the game
Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
10 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments