Python's simplicity philosophy
Rainer Deyke
rainerd at eldwood.com
Fri Nov 14 21:55:10 EST 2003
Douglas Alan wrote:
> Q: How do I sum a sequence of numbers?
In three lines:
x = 0
for element in seq:
x += element
In two lines:
> A: from operator import add
> reduce(add, seq)
Unless seq is empty, in which case you need this:
from operator import add
reduce(add, seq, 0)
In one line:
x = sum(seq)
And that is why 'sum' is a worthwhile part of the Python standard library
and 'reduce' is not: using 'sum' is significantly shorter than using a for
loop, while using 'reduce' is not.
--
Rainer Deyke - rainerd at eldwood.com - http://eldwood.com
More information about the Python-list
mailing list