Consider the following (working) Python code:

import sys

def sum(list):
    # total = 0 does not work for non-numeric types
    total = list[0].__class__()
    for v in list:
        total += v
    return total

l = [1, 2, 3]
print sum(l)

l = [1.1, 2.2, 3.3]
print sum(l)

l = ["a", "b", "c"]
print sum(l)

In order for sum() to be generic I initialize total to the value of 
list[0].__class__().  This works but I would like to know if this is the 
correct or preferred way of doing it.  It means that sum() must be given a 
list whose elements are types or classes that have a no-arg constructor 
(through this is probably almost always the case).

Thanks,
Edward


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to