What is the difference between random randint and randrange?
https://github.com/python/cpython/blob/.../Lib/random.py#L218
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
The docs on randrange
say:
random.randrange([start], stop[, step])
Return a randomly selected element from
range(start, stop, step)
. This is equivalent tochoice(range(start, stop, step))
, but doesn’t actually build a range object.
And range(start, stop)
returns [start, start+step, ..., stop-1]
, not [start, start+step, ..., stop]
. As for why... zero-based counting rules and range(n)
should return n
elements, I suppose. Most useful for getting a random index, I suppose.
While randint
is documented as:
random.randint(a, b)
Return a random integer N such that
a <= N <= b
. Alias forrandrange(a, b+1)
So randint
is for when you have the maximum and minimum value for the random number you want.