Initialization of variables using no-arg constructor

Paul Rubin http
Tue Oct 10 00:26:33 CEST 2006


> 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.

More natural would be (untested):

    def sum(list):
       assert list    # both versions fail if list is empty
       total = list[0]

       # could use list[1:] but this avoids copying
       for i in xrange(1, len(list)):
          total += list[i]

or various alternate spellings with iterators, the reduce function, etc.

This pattern is common enough that Haskell has a "foldl1" function
similar to reduce but initializing from the first element of the sequence.



More information about the Python-list mailing list