Initialization of variables using no-arg constructor
Calvin Spealman
ironfroggy at gmail.com
Tue Oct 10 00:26:29 CEST 2006
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).
>
> Thanks,
> Edward
First of all, you never need to initialize the total to 0 of some
specific type. You can just start with list[0] as the total and
iterate over all the remaining values.
Of course, you could just use reduce(lambda a,b: a+b, the_list) instead.
Of course, you should never use list as a name, its a builtin already.
Of course, you could just use the sum builtin (for numbers).
--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
More information about the Python-list
mailing list