Initialization of variables using no-arg constructor
Tue Oct 10 00:26:33 CEST 2006
> In order for sum() to be generic I initialize total to the value of
> list.__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):
assert list # both versions fail if list is empty
total = list
# 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