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

I need to pick out "x" number of non-repeating, random numbers out of a list. For example:

all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]

How do I pick out a list like [2, 11, 15] and not [3, 8, 8]?


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 = set(population)
samples = random.sample(population, 3)

Something like this:

all_data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
from random import shuffle
shuffle(all_data)
res = all_data[:3]# or any other number of items

OR:

from random import sample
number_of_items = 4
sample(all_data, number_of_items)

If all_data could contains duplicate entries than modify your code to remove duplicates first and then use shuffle or sample:

all_data = list(set(all_data))
shuffle(all_data)
res = all_data[:3]# or any other number of items

Others have suggested that you use random.sample. While this is a valid suggestion, there is one subtlety that everyone has ignored:

If the population contains repeats, then each occurrence is a possible selection in the sample.

Thus, you need to turn your list into a set, to avoid repeated values:

import random
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
random.sample(set(L), x) # where x is the number of samples that you want

Another way, of course with all the solutions you have to be sure that there are at least 3 unique values in the original list.

all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15]
choices = []
while len(choices) < 3:
    selection = random.choice(all_data)
    if selection not in choices:
        choices.append(selection)
print choices 

You can also generate a list of random choices, using itertools.combinations and random.shuffle.

all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15]

# Remove duplicates
unique_data = set(all_data)

# Generate a list of combinations of three elements
list_of_three = list(itertools.combinations(unique_data, 3))

# Shuffle the list of combinations of three elements
random.shuffle(list_of_three)

Output:

[(2, 5, 15), (11, 13, 15), (3, 10, 15), (1, 6, 9), (1, 7, 8), ...]