112

Lets say I have class C which has attribute a.

What is the best way to get the sum of a from a list of C in Python?


I've tried the following code, but I know that's not the right way to do it:

for c in c_list:
    total += c.a
Georgy
  • 12,464
  • 7
  • 65
  • 73
jsj
  • 9,019
  • 17
  • 58
  • 103

4 Answers4

248

Use a generator expression:

sum(c.a for c in c_list)
Georgy
  • 12,464
  • 7
  • 65
  • 73
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I like the simplicity, but it seems to take half again as long as (c1.A + c2.A + c3.A) for about 10 elements where c.A is a float. – jcomeau_ictx Jan 06 '16 at 19:52
9

If you are looking for other measures than sum, e.g. mean/standard deviation, you can use NumPy and do:

mean = np.mean([c.a for c in c_list])
sd = np.std([c.a for c in c_list])
Georgy
  • 12,464
  • 7
  • 65
  • 73
Heribert
  • 613
  • 1
  • 9
  • 27
6

I had a similar task, but mine involved summing a time duration as your attribute c.a. Combining this with another question asked here, I came up with

sum((c.a for c in cList), timedelta())

Because, as mentioned in the link, sum needs a starting value.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Bill Kidd
  • 1,130
  • 11
  • 13
2

Use built-in statistics module:

import statistics

statistics.mean((o.val for o in my_objs))
Shital Shah
  • 63,284
  • 17
  • 238
  • 185