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

PythonListRandom

Python Problem Overview


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]?

Python Solutions


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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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 

Solution 5 - Python

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), ...]

Solution 6 - Python

import random
fruits_in_store = ['apple','mango','orange','pineapple','fig','grapes','guava','litchi','almond'] 
print('items available in store :')
print(fruits_in_store)
my_cart = []
for i in range(4):
    #selecting a random index
    temp = int(random.random()*len(fruits_in_store))
    # adding element at random index to new list
    my_cart.append(fruits_in_store[temp])
    # removing the add element from original list
    fruits_in_store.pop(temp)  
print('items successfully added to cart:')
print(my_cart)

Output:

items available in store :
['apple', 'mango', 'orange', 'pineapple', 'fig', 'grapes', 'guava', 'litchi', 'almond']
items successfully added to cart:
['orange', 'pineapple', 'mango', 'almond']

Solution 7 - Python

If the data being repeated implies that we are more likely to draw that particular data, we can't turn it into a set right away (since we would loose that information by doing so). For this, we need to pick samples one by one and verify the size of the set that we generate has reached x (the number of samples that we want). Something like:

data=[0, 1, 2, 3, 4, 4, 4, 4, 5, 5, 6, 6]
x=3
res=set()
while(len(res)<x):
    res.add(np.random.choice(data))
print(res)

some outputs :

{3, 4, 5}
{3, 5, 6}
{0, 4, 5}
{2, 4, 5}

As we can see 4 or 5 appear more frequently (I know 4 examples is not good enough statistics).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge View Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonArtsiom RudzenkaView Answer on Stackoverflow
Solution 3 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 4 - PythonJoeView Answer on Stackoverflow
Solution 5 - PythonrizaView Answer on Stackoverflow
Solution 6 - PythonShashank RautelaView Answer on Stackoverflow
Solution 7 - PythongurcaniView Answer on Stackoverflow