The Python Oracle

How to randomly change boolean value in a list

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation

--

Chapters
00:00 Question
00:47 Accepted answer (Score 7)
01:30 Answer 2 (Score 1)
01:43 Answer 3 (Score 1)
02:15 Thank you

--

Full question
https://stackoverflow.com/questions/6074...

Accepted answer links:
[random.randint(a, b)]: https://docs.python.org/3/library/random...
[randrange(a, b)]: https://docs.python.org/3/library/random...

Answer 3 links:
[documentation]: https://docs.python.org/2/library/random...

--

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