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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With