Reputation: 67
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?
Upvotes: 4
Views: 181
Reputation: 3718
try :
for x in population:
if x:
r = random.randint(0, len(population)-1)
population[r] = True
Upvotes: 1
Reputation: 59974
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.
Upvotes: 7
Reputation: 12181
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
.
Upvotes: 1