Sum / Average an attribute of a list of objects

jsj picture jsj · Jun 4, 2012 · Viewed 41.3k times · Source

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

Answer

phihag picture phihag · Jun 4, 2012

Use a generator expression:

sum(c.a for c in c_list)