11

I want a one-liner solution in Python of the following code, but how?

total = 0
for ob in self.oblist:
    total += sum(v.amount for v in ob.anoutherob)

It returns the total value. I want it in a one-liner. How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nazmul Hasan
  • 6,840
  • 13
  • 36
  • 37
  • The canonical is *[How can I put multiple statements in one line?](https://stackoverflow.com/questions/6167127/)* (though it was posted later). – Peter Mortensen Oct 04 '22 at 20:09

2 Answers2

40

There isn't any need to double up on the sum() calls:

total = sum(v.amount for ob in self.oblist for v in ob.anotherob)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
7

You can just collapse the for loop into another level of comprehension:

total = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)
Amber
  • 507,862
  • 82
  • 626
  • 550