To generate n random numbers, use generators : p>
numbers = (random.randint(1, 100) for _ in range(n))
Note: If the list of numbers is used for more than just calculating the sum, do not use a generator, but rather list comprehension (just switch from ()
to []
):
numbers = [random.randint(1, 100) for _ in range(n)]
Where n
is the number of numbers to be generated. Note that if you do print(numbers)
, the output will be:
<generator object <genexpr> at ...>
That is, the list itself has not yet been generated. Even so, to get the sum of the values, just use the native function sum
:
total = sum(numbers)
By doing print(total)
, an integer value referring to the sum of all numbers is displayed. In my case, the total was 300.
See working on Ideone .