Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum / Average an attribute of a list of objects

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 
like image 547
jsj Avatar asked Jun 04 '12 10:06

jsj


People also ask

How do you sum a list of objects in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

Can you sum a list in Python?

Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.


1 Answers

Use a generator expression:

sum(c.a for c in c_list) 
like image 78
phihag Avatar answered Sep 29 '22 09:09

phihag