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

Viewed 67104

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

7 Answers
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']

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

Related