If you need to reproduce the results, you can seed the random generator, for instance with random.seed(123)
. This way, every time you run the code you get the same random result.
In this case, the accepted solution offered by bvidal it would look like this:
import random
l = list(range(10)) # example list (please notice the explicit call to 'list')
random.seed(123)
random.shuffle(l) # shuffle the list
print(l) # outputs [8, 7, 5, 9, 2, 3, 6, 1, 4, 0]
index_value = random.sample(list(enumerate(l)), 2)
print(index_value) # outputs [(8, 4), (9, 0)]
Another approach is to use the random sample function random.sample
from the standard library to randomly get an array of indices and use those indices to randomly choose elements from the list. The simplest way to access the elements is converting the list to a numpy array:
import numpy as np
import random
l = [1, -5, 4, 2, 7, 4, 8, 0, 9, 3]
print(l) # prints the list
random.seed(1234) # seed the random generator for reproducing the results
random_indices = random.sample(range(len(l)), 2) # get 2 random indices
print(random_indices) # prints the indices
a = np.asarray(l) # convert to array
print(list(a[random_indices])) # prints the elements
The output of the code is:
[1, -5, 4, 2, 7, 4, 8, 0, 9, 3]
[7, 1]
[0, -5]
IndexError
to give more details