Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly change boolean value in a list

Tags:

python

I'm trying to randomly assign a 'True' value to a list of booleans. When I run the code, I keep getting an error. Here's the code:

    for x in population:
        if x:
            r = random.randint(0, len(population))
            population[r] = True

Which keeps throwing the error:

"Traceback (most recent call last):
     population[r] = True
 IndexError: list assignment index out of range"

I'm sure it's something trivial, but I can't figure it out. How is the index assignment out of range when I constrain it to within the length of the list?

like image 300
agiuchin Avatar asked Jan 01 '23 05:01

agiuchin


1 Answers

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.

like image 113
TerryA Avatar answered Jan 05 '23 17:01

TerryA