Search code examples
pythonpython-3.xloopsrandom

How to generate a unique single random number each time in a loop in Python?


I know there are some similar questions,but all of them just return a list,I just need a number,each time random generate a unique single number:

Now I'm using Python to build a loop:

for _ in range(9):
        random_number=random.randint(1,11)
        print(random_number)

My question is how to make sure each time the random_number is unique,not repeating in all 9 times. I don't need a list,just the random_number


Solution

  • You can use random.sample over the target range of numbers to pick a desired number of unique numbers from them:

    import random
    for random_number in random.sample(range(1, 12), 9):
        print(random_number)