I want to sum up an instance variable of a class object in a list of that class object.
Class A(object):
def __init__(self):
self.a = 20
B = []
for i in range(10):
B.append(A())
# Can this be made more pythonic?
sum = 0
for i in B:
sum += i.a
I was thinking along the lines of using a map function or something? Don't know if that's pushing it too much though. Just curious.
sum(i.a for i in B)(See: the tutorials on list comprehensions and generator expressions.)map()andfilter().)sum = 0somewhere in your script. This shows why it's bad to name your variablessum.sum()is a builtin function in it, not your variable.)