On 10/9/06, Edward Waugh <edward_waugh at hotmail.com> wrote:
> 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).
>
I'd do this:
>>> def sum(list):
... total = list[0]
... for v in list[1:]:
... total += v
... return total
I'm not sure if regular slice notation makes a copy of the list or
not, if it does you can use itertools:
>>> def sum(list):
... total = list[0]
... for v in itertools.islice(list, 1, len(list)):
... total += v
... return total
> Thanks,
> Edward
>