-3

In my code I am attempting to generate 8 random numbers using a for loop. I then add these to the end of my array of the name 'numbers'. Now I will like to add the numbers in this array together but I can't figure out a way to do this. Below you will see my code.

    def get_key():
        numbers = []
        for i in range(8):
            i = random.randrange(33, 126)
            numbers.append(i)


    get_key()
  • 3
    Possible duplicate of [sum a list of numbers in Python](http://stackoverflow.com/questions/4362586/sum-a-list-of-numbers-in-python) – idjaw Feb 26 '16 at 19:09

3 Answers3

2

You want to use sum

a = [1,2,3,4,5]

sum(a) # outputs 15
idjaw
  • 25,487
  • 7
  • 64
  • 83
0

add as in sum? simply do sum(numbers).

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

As others have noted, you can use sum to iterate and accumulate over the list (the default accumulator for sum is int(), i.e. 0). Also, if this is the only purpose for the list, you can save memory by using a generator.

import random

get_key = lambda: sum(random.randrange(33, 126) for _ in range(8))
print( get_key() ) # 612

The real question is why are you trying to do this? It seems like there will be a more direct method by using a higher-level distribution. For example, the sum of n I.I.D. variables will approach a Normal distribution.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36