0

I am looking for an efficient way (pseudocode will do) to choose a given number of values randomly from the list preferably "Pythonic way". Values have to come from unique indexes of the list

So for example:

list = [0,1,2,3,4,5,24]

def choose(number_of_values, list):
    # method

return_val = choose(3, list)
# return_val = [2, 4, 3]
Bato-Bair Tsyrenov
  • 1,174
  • 3
  • 17
  • 40
  • 2
    Most pythonic way ever `random.sample(list, 4)` P.s DONT name your variables as `list` as they shadow the builtin – Bhargav Rao Apr 16 '15 at 16:22
  • Take a look at this: [https://docs.python.org/2/library/random.html](https://docs.python.org/2/library/random.html) – Chan Kha Vu Apr 16 '15 at 16:23

2 Answers2

2

Its what that random.sample is for.

>>> import random
>>> random.sample([0,1,2,3,4,5,24],3)
[2, 24, 5]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Use a for loop and append the random choices to a list, then return. Also, don't use list as a variable name, it shadows the built-in.

import random

def choose(number_of_values, lst):
    _temp = []
    for i in range(number_of_values):
        _temp.append(random.choice(lst))
    return _temp
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76