I'm trying to create a code that produces a list of 5 different random number. Here is my current code:
import random
rN0 = random.randint(1, 50)
rN1 = random.randint(1, 50)
rN2 = random.randint(1, 50)
rN3 = random.randint(1, 50)
rN4 = random.randint(1, 50)
randomNumber = [rN0, rN1, rN2, rN3, rN4]
But, sometimes it produces two or more of the same number in the list. I would like each number in the list to be unique every time. Help please?
CodePudding user response:
Try:
import random
def newNum(nums):
while True:
n = random.randint(1, 50)
if n in nums:
continue
return n
randomNumber = []
for _ in range(5):
n = newNum(randomNumber)
randomNumber.append(n)
print(randomNumber)
Or:
import random
randomNumber = random.choices(range(1, 51), k=5)
print(randomNumber)
CodePudding user response:
You can use random.sample
that picks n random numbers from a given range
:
>>> random.sample(range(1, 50), 5)
[4, 41, 16, 40, 25]