[Tutor] Adding all numbers in a file or list

aug dawg augdawg09 at gmail.com
Wed Aug 25 02:55:34 CEST 2010


Got it. Thanks everyone!


On Tue, Aug 24, 2010 at 6:22 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Wed, 25 Aug 2010 02:23:10 am Nitin Das wrote:
> > alternatively you can use the lambda , reduce function for summing up
> > all the numbers in a list for e.g:-
> >
> > lis = [1,2,3,4,5]
> > p = reduce(lambda x,y : x+y, lis)
> >
> > p will have the value = 15.
>
> Sure, you *can* do this, by why would you re-invent the wheel like that?
> As an exercise to teach reduce, sure, or as a demonstration of lambda,
> or if you have to support Python 2.2 or older (but that's like four
> versions out of date!). sum() is really the only sensible way to do it
> these days.
>
> But if you insist on using reduce like that, it will probably be much
> faster to do this:
>
> import operator
> reduce(operator.add, lis)
>
>
> particularly on the older versions where sum() isn't available.
>
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100824/bdf95aeb/attachment-0001.html>


More information about the Tutor mailing list