Sum of the integers in a List

November 25th, 2007 00:05

I had to write some code recently which calculated the sum of the integers stored in a List. I went the longhand way about it and wrote something like:

i_list = [ 1, 2, 3, 4]

total = 0
for n in i_list:
  total += n

Of course the simplest way to do it is:

i_list = [ 1, 2, 3, 4]

total = sum(i_list)

So I wrote a very simple timing test to see if there was a significant performance hit:

def longhand(i_list):
    total = 0
    for i in i_list:
        total += i
    return total

def shorthand(i_list):
    return sum(i_list)

i_list = []
for i in range(0, 1000000):
    i_list.append(i)

import time

s = time.time()
x = shorthand(i_list)
#x = longhand(i_list)
f = time.time()

duration = f - s

print duration

I did ten runs using each method to sum the list of one million integers and the shorthand averaged 0.34 seconds while the longhand method averaged 0.51 seconds. If you are using small lists then the difference will be negligible but for very large lists you will benefit from using the sum builtin.

Leave a Reply