I need 3 unique random numbers between 1 to 20.
I have a loop generating 3 random numbers from 1-20. And I don't want there to be any repeats. I have something that works for the first two numbers. But in my code the first and third numbers can still be the same which needs to be fixed.
i = 1
while i <= 3:
x = random.randint(1, 20)
print(choice([i for i in range(1, 20) if i != [x]]))
i += 1
Is there a better way to achieve this in Python?
You can use random.sample()
. Below example will return you 3 unique random numbers between 1 to 20.
>>> import random
>>> sample_count = 3 # count of required unique numbers
>>> start_range, end_range = 1, 20 # start and end range
>>> random.sample(range(start_range, end_range+1), sample_count)
[4, 1, 14]
Please refer random.sample() documentation for more details.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments