Sum / Average an attribute of a list of objects

attributes, list, python, sum

Solution

Use a generator expression:

sum(c.a for c in c_list)

Problem

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

Original source

Related problems