Q:

python, adding and overwriting a value in a list

I am making a list called foo with n random values stored in it. I want to be able to make a loop that continuously adds random values and stores the new value in foo[i] this is my code so far. Anytime I run this I am unable to exit the while loop.
import random
foo=[]
i=0
flag = False

print("How many horses do you want to race?")
horses = eval(input())
print (horses)

while flag == False:
    for i in range(horses):
        foo.insert(i, random.randrange(4,41))
    print(a)
    if foo[i] >= 5280:
        flag = True
    else:
        i=i+1

I think the reason this is not working is because I'm not actually adding to the value stored in foo[i] in the line
        foo.insert(i, random.randrange(4,41))

but I am unable to figure out what to do instead. Thanks for any help!

A:

You probably want to change it to:
import random

i=0
flag = False

print("How many horses do you want to race?")
horses = int(input())
print (horses)

foo = [0] * horses #initialize horse values
while not flag:
    for i in range(horses):
        foo[i] += random.randrange(4,41) #move the horse a random amount
        if foo[i] >= 5280:
            flag = True #a horse has won
            break #exit the loop

I:

deleted the a variable that you were not initializing
took out using the i variable outside the loop (which you shouldn't do)
fixed the line to actually add to the horse
initialized all of the horses at 0
put the line with the loop exit inside the loop so it exits during the loop
took out flag == False and replaced it with not flag:

From PEP 8: Don't compare boolean values to True or False using == .

