kramer65 kramer65 - 5 months ago 8
Python Question

How to pythonically make a total count of all counts in a list of objects?

In Python I've got a list of objects which have a

.count()
method. I now want a total count of all objects. The following works:

count = 0
for the_obj in obj_list:
count += the_obj.count()
print count


but I've got the feeling that there are more Pythonic ways of doing this. Anybody has a tip?

Answer

You can use the built-in sum() with a generator to sum the individual counts.

count = sum(obj.count() for obj in obj_list)

Alternatively (although not necessary), a functional approach would be to use reduce and map, with methodcaller to call the method.

from operator import add, methodcaller
count = reduce(add, map(methodcaller('count'), obj_list))