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
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.
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.
Use a generator expression:
sum(c.a for c in c_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With