[Tutor] The better Python approach

Alan Gauld alan.gauld at btinternet.com
Thu Jan 22 00:25:18 CET 2009


"Robert Berman" <bermanrl at cfl.rr.com> wrote

> Wow! That is all worth knowing. I am  fascinated by the  single sum 
> over a double loop.
>
> > or more simply as a single sum over a double loop:
> >  bigtotal = sum(int(x) for line in myfile for x in line.split())
>
> > which you may or may not see as an improvement...

And that nicely illustrates the caveat with using the most concise 
form.
You have to make a judgement about when it becomes too concise
to be readable and therefore maintainable. Personally I prefer the
double loop to the double sum, but in practice I'd probably have
been happy to stick with the outer for loop and only one sum() call
inside that.

But that uis where taste comes into programming, there is no absolute
correct form - which takes us back to your original post! :-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list