Re: Initialization of variables using no-arg constructor

2006-10-10 Thread jordanrastrick
Just to expand a little on what others have already said - not only is the total = list[0] etc.approach more readable, idiomatic, and elegant, IMO its more semantically correct. Your constraint that list[0].__class__ has a no-arg constructor is not strong enough; a more subtle and potentially bug-

Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Ben Finney
"Edward Waugh" <[EMAIL PROTECTED]> writes: > 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 Your function assumes t

Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Paul Rubin
"Chris Mellon" <[EMAIL PROTECTED]> writes: > 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 > ... retu

Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Paul Rubin
> 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

Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Calvin Spealman
On 10/9/06, Edward Waugh <[EMAIL PROTECTED]> 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

Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Chris Mellon
On 10/9/06, Edward Waugh <[EMAIL PROTECTED]> 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

Initialization of variables using no-arg constructor

2006-10-09 Thread Edward Waugh
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"] pri