How to randomly change boolean value in a list
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 How To Randomly Change Boolean Value In A List
00:38 Accepted Answer Score 7
01:24 Answer 2 Score 1
01:58 Answer 3 Score 1
02:09 Thank you
--
Full question
https://stackoverflow.com/questions/6074...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 How To Randomly Change Boolean Value In A List
00:38 Accepted Answer Score 7
01:24 Answer 2 Score 1
01:58 Answer 3 Score 1
02:09 Thank you
--
Full question
https://stackoverflow.com/questions/6074...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 7
random.randint(a, b) returns a number between a and b inclusive. If the result of the function call equals len(population), then you're trying to do population[len(population)], which will raise an IndexError because indexing starts at 0.
Simple change: Just minus 1 from len(population):
r = random.randint(0, len(population)-1)
Or use randrange(a, b), which is not inclusive:
r = random.randrange(len(population))
Note that if the first argument is 0 we don't need it since it will assume the start is 0.
ANSWER 2
Score 1
According to the documentation, random.randint(a, b)
Return a random integer N such that
a <= N <= b.
Since arrays are indexed starting at 0 in Python, len(population) is outside the range of the array (hence your error). As @TerryA indicated, you actually want the range to be from 0 to len(population) - 1.
ANSWER 3
Score 1
try :
for x in population:
if x:
r = random.randint(0, len(population)-1)
population[r] = True