Can someone explain why the range
in the random.randint(0, len(messages) - 1)
has a minus 1 at the end? The list has 9 values:
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
select_number = random.randint(0, len(messages) - 1)
list_select = messages[select_number]
print(list_select)
random.randint()
's second value is inclusive . It'll pick a number from 10 random integers ( 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
and 9
), where you only have 9 indices in the list. len(messages)
is 9
, but there is no messages[9]
index, as Python indexing starts at 0
. Instead, the only valid indices go from 0
to 8
.
So by using random.randint(0, len(messages) - 1)
, the function is limited to picking a valid index for the messages
list.
The code should instead use random.choice()
, which picks a random element from a list:
list_select = random.choice(messages)
In other situations, random.randrange()
could be an option too, as it doesn't include the endpoint in the possible values, working analogous to Python indexing, slicing and range()
:
index_select = random.randrange(len(messages))
This is because random.randint
picks the indexes of the list, from 0 to 8 at random, and selects a message.
Now, the indexes of a list goes from 0
to len(messages)-1=8
.
According to the docs: https://docs.python.org/3/library/random.html#random.randint
random.randint(a, b) . Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
Which means an integer between 0 and 8 is picked, which are the valid indexes of the list, If we have instead put len(messages)
, index 9 would have been picked too which is an invalid index for a list in Python, since Python lists are 0-indexed
random.randint(a, b)
Return a random integer N such that a <= N <= b.
len(messages) - 1
Is a bit tricky because range of your list is indeed 9 but you have to remember that counting is starting from 0 instead of 1. So in your case len(messages)
is going to return 9 but the first element is in messages[0]
It means that in your case the select_number = random.randint(0, len(messages) - 1)
will give number from 0 to len(messages) - 1
which is 9 - 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.