[Tutor] The better Python approach

Kent Johnson kent37 at tds.net
Wed Jan 21 20:47:36 CET 2009

On Wed, Jan 21, 2009 at 2:02 PM, Robert Berman <bermanrl at cfl.rr.com> wrote:

>   myfile = openinput()
>   for line in myfile:
>       jlist = line.split()
>       for x in jlist:
>           bigtotal += int(x)

Python has a sum() function that sums the elements of a numeric
sequence, so the inner loop can be written as
  bigtotal += sum(int(x) for x in line.split())

But this is just summing another sequence - the line sums - so the
whole thing can be written as
  bigtotal = sum(sum(int(x) for x in line.split()) for line in myfile)

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


More information about the Tutor mailing list