Search code examples
pythonnumberssum

How to sum a list of numbers in python


So first of all, I need to extract the numbers from a range of 455,111,451, to 455,112,000. I could do this manually, there's only 50 numbers I need, but that's not the point.

I tried to:

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

What should I do?


Solution

  • Use sum

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

    It is a builtin function, Which means you don't need to import anything or do anything special to use it. you should always consult the documentation, or the tutorials before you come asking here, in case it already exists - also, StackOverflow has a search function that could have helped you find an answer to your problem as well.


    The sum function in this case, takes a list of integers, and incrementally adds them to eachother, in a similar fashion as 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