ban can ban can - 7 months ago 33
Python Question

How to add 2 random numbers from a list together?

For example:

list1 = [1,2,3,4,5,6]

I want to get 2 random numbers from this list and add them together:

3 + 2
for example.


For unique selections (sampling without replacement), you can make use of random.sample for selecting multiple random elements from the list and use the built-in sum.

>>> list1 = [1,2,3,4,5,6]
>>> from random import sample
>>> sum(sample(list1, 2))

A 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\", 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))

Obviously when sampling with replacement, the sample size can be larger than the size of the population.

>>> sum(choice(list1) for _ in range(1000))