How to sum a list of numbers in python

So, first of all, I need to extract numbers from the range 455111,451, up to 455, 112 000. I could do it manually, I only need 50 numbers, but it is not.

I tried:

for a in range(49999951,50000000): print +str(a) 

What should I do?

+4
source share
3 answers

Use sum

 >>> sum(range(49999951,50000000)) 2449998775L 

This is a built-in function , which means that you do not need to import anything or do something special to use it. You should always consult the documentation or study guides before you start asking here if it already exists. In addition, StackOverflow has a search function that could help you find the answer to your problem.


The sum function in this case takes a list of integers and adds them step by step to eachother, similar to the way below

 >>> total = 0 >>> for i in range(49999951,50000000): total += i >>> total 2449998775L 

Also - similar to Reduce :

 >>> reduce(lambda x,y: x+y, range(49999951,50000000)) 2449998775L 
+13
source

sum is the obvious way, but if you had a massive range and calculate the sum by increasing each number each time, this can be done mathematically instead (as shown in sum_range ):

 start = 49999951 end = 50000000 total = sum(range(start, end)) def sum_range(start, end): return (end * (end + 1) / 2) - (start - 1) * start / 2 print total print sum_range(start, end) 

Outputs:

 2449998775 2499998775 
+5
source

I have no good question if you want to have a sum of numbers

 sum = 0 for a in range(x,y): sum += a print sum 

if you want to have numbers in the list:

 lst = [] for a in range(x,y): lst.append(a) print lst 
0
source

Source: https://habr.com/ru/post/1489739/


All Articles