If you are referring to link , the problem is that it is probably using a fixed seed in your random number generator . My guess is that this is being done so that the results are always deterministic. By chance, the first two calls of random.randint(0,9)
returned the same value ( 6
) for the seed used (1 chance in 10 to happen, and it happened!) And so seemed that the value was not overwritten, when in fact it was.
Try to assign a seed to random
yourself, and you should have different results. In my case, I got a list with 4 elements using:
import random
random.seed(10);
list_num = []
c = 0
v = random.randint(0, 9)
while c < 4 and v not in list_num:
list_num.append(v)
c += 1
v = random.randint(0, 9)
You can always, of course, use the clock as a seed, so that the execution is different every time.
And as for the original problem ("generating a list of 4 random integers that do not repeat"), this code needs to be adapted because it is simply stopping when it encounters the first one that repeats itself ... I suggest the following: ( care: if the number of elements you request is greater than the number of elements available, this code will go into an infinite loop)
while c < 4:
while v in list_num:
v = random.randint(0, 9)
list_num.append(v)
c += 1
I tried the python tutor without using any seed, and got [6, 0, 4, 8]
.