Search code examples
python-3.xsampling

How to randomly select elements from an array in python?


I need to randomly select elements from a list. Currently, I will sometimes select too many copies of an element from the original list eg:

Original List: [0, 1, 2, 3, 4]

3 Randomly Selected Elements: [4, 4, 4]

I do not want multiple 4s selected if there was only 1 in the original list.

What should I do to not take more copies of a value than exists in the first array?


Solution

  • A solution is to remove the elements from the original list when you select them.

    import random 
    original_list = [1, 2, 2, 3, 3, 3]
    number_of_random_selections = 4
    random_selections = []
    
    for i in range(0, len(original_list)):
        random_index = random.randint(0, number_of_random_selections)
        random_selection = original_list[random_index]
        random_selections.append(random_selection)
        original_list.remove(random_selection)
    
    print(random_selections)