It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...).
Is there any reason for this apparent inconsistency?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I tried to get to the bottom of this by examining some old sources. I suspected that
randintwas implemented before Python’s long integer: meaning that if you wanted a random number that includedINT_MAX, you would have needed to callrandom.randrange(0, INT_MAX + 1)which would have overflowed and resulted in arguments of(0, 0)or(0, INT_MIN)depending.However, looking as far back as even the Python 1.5.2 sources, in
Lib/whrandom.pywe see:whrandom.randintwas continued to be deprecated in 2.0, 2.1, 2.2, and 2.3; butrandom.randintwas marked as deprecated in 2.1, although no longer marked as deprecated in 2.2.Also,
random.pyfrom version 2.1 is the first to note inrandom.randint‘s docstring:The only available source older than that is the 0.9.1 source, and as far as I can tell,
randintwas not implemented at that point.Thus, I conclude that the reasoning for
randintincluding the endpoint is known to only Guido himself at this point; given the docstring from Python 2.1, it sounds like the reason may have been a simple mistake.