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