3

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.

ban can
  • 77
  • 6

5 Answers5

4

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
miradulo
  • 28,857
  • 6
  • 80
  • 93
1

Here you have the solution, but what I'd like to tell you is that you wont go too far in programming by asking that kind of questions.

What you need to do before asking is to do some reflexion. for example, if I were you, I would have searched:

On google "python get random number list" > How do I randomly select an item from a list using Python?.

from random import choice

result = choice(list1) + choice(list1)

Good luck!

Community
  • 1
  • 1
  • As this is a poor question, it could be usefull to provide a more general answer so it could maybe be usefull to futures reader. For example, how to sum to differrent randomly selected element? And what if I want to sum 3, 4 or N elements? – Delgan Jul 14 '16 at 09:03
  • @bancan Yep! take a look to the update, it will help you :) –  Jul 14 '16 at 09:04
  • I was too specific while searching for an answer on google. Next time I'll try to be less specific. Thanks for the help – ban can Jul 14 '16 at 09:05
1

I guess that if you want distinct elements, you can use:

import random

sum(random.sample(list1, 2))
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
1

For taking random numbers from the list you can use

import random
random.choice()

In your case use

import random
list1 = [1,2,3,4,5,6]
sum=random.choice(list1)+random.choice(list1)
miradulo
  • 28,857
  • 6
  • 80
  • 93
1

You should use the function:

from random import choice
a=(random.choice(list1))

'a' will now be a random number from the list

Joseph M
  • 84
  • 1
  • 7