ban can - 6 months ago 27

Python Question

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`

Answer

**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))
7
```

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\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
```