lundi 8 avril 2019

How to remove duplicate number within a list and then replace with a new random number

new to python. I'm trying to make a lottery-styled thing, where the for loop appends 5 random numbers into a list. Let's say the list so far is nList = [1,2,3,4] and the last iteration happens to also be a 4. I want the code to remove the extra 4 that was supposed to be in the last index, and replace it with a brand new random number that does NOT duplicate any of the rest of the numbers on the list. I can't seem to wrap my head around it.

I've tried using nList.pop(), and that solves the problem of removing the duplicate, I just don't know how to add the new random number.

import random
nList = []
random.seed()
for x in range(5):
    n = random.randint(1,39)
    for item in nList:
       if n == item:
            nList.pop()
    else:
        nList.append(n)

print(nList)

I just end up with a smaller list, which is not what I want.




Aucun commentaire:

Enregistrer un commentaire