-1

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?

Branson Smith
  • 462
  • 2
  • 13
Iago Lemos
  • 85
  • 1
  • 5

1 Answers1

-1

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)
Branson Smith
  • 462
  • 2
  • 13
  • You already imported `random` but not use functions from it. Also modifying original list is not the best idea. – Olvin Roght Jan 27 '20 at 19:50
  • I agree that the original list should not be changed, but was hoping to provide a solution that was focused on answering the asker's specific question, and leave those decisions to him. Also, I imported random for the randint() function. It sounds like you could help both me and OP by providing an improved answer :) – Branson Smith Jan 27 '20 at 19:58
  • [`random.sample(original_list, number_of_random_selections)`](https://docs.python.org/3/library/random.html#random.sample) – Olvin Roght Jan 27 '20 at 20:02