list1 = [1,2,3,4,5,6]
3 + 2
>>> list1 = [1,2,3,4,5,6] >>> from random import sample >>> sum(sample(list1, 2)) 7
ValueError will be raised if you attempt to obtain a sample larger than your list (or more generally, population) size.
>>> sum(sample(list1, len(list1) + 1)) File "D:\Anaconda\lib\random.py", line 315, in sample raise ValueError("Sample larger than population") ValueError: Sample larger than population
For non-unique selections (sampling with replacement), a simple approach for small samples is just repeatedly calling
random.choice for whatever sample size you require.
>>> from random import choice >>> sum(choice(list1) for _ in range(2)) 6
Obviously when sampling with replacement, the sample size can be larger than the size of the population.
>>> sum(choice(list1) for _ in range(1000)) 3527