first of all, i'd like to say that i thought the exact same question were answered before, but after a brief research i couldn't find any threads leading me to the answer that i wanted in here which means i didn't dig enough or missed some keywords. Sorry for that if that question is out there.
Anyways, i've started to learn python and was going through some exercises. I needed to create a list which has 10 randomly generated integers in it and each integer must have a different value.
So i've tried to compare the first element of the list with the next one and if they're the same, i tried to generate a new number with the if statement.
import random
listA = []
for i in range(0,10):
x=random.randint(1,100)
if listA[i] == listA[i-1]:
x=random.randint(1,100)
else:
listA.append(x)
listA.sort()
print(listA)
But i've got an error saying; "list index is out of range"
i've expected the if statement start with the "0" index and count till the 9th index of the "listA" and as it goes, compare them, if the same, generate another random number. But obviously, my indexation was wrong.
Also any other comment on the code would be appriciated.
Thanks for your time in advance.
Aucun commentaire:
Enregistrer un commentaire