How do you pick “x” number of unique numbers from a list in Python?

That’s exactly what random.sample() does.

>>> random.sample(range(1, 16), 3)
[11, 10, 2]

Edit: I’m almost certain this is not what you asked, but I was pushed to include this comment: If the population you want to take samples from contains duplicates, you have to remove them first:

population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = list(set(population))
samples = random.sample(population, 3)

Leave a Comment

tech