1

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.

6
  • 2
    sum(i.a for i in B) (See: the tutorials on list comprehensions and generator expressions.) Commented Sep 5, 2013 at 0:44
  • 1
    (As much as I dislike abusing the term "pythonic", I'd argue that list comprehensions are clearly more so than map() and filter().) Commented Sep 5, 2013 at 0:47
  • @millimoose..This is actually giving me a TypeError saying 'int' object is not callable Commented Sep 5, 2013 at 0:50
  • 3
    @Nitin That's probably because you still have sum = 0 somewhere in your script. This shows why it's bad to name your variables sum. Commented Sep 5, 2013 at 0:56
  • 1
    @Nitin The error is somewhere else than in my suggestion: ideone.com/Dx7v2I (sum() is a builtin function in it, not your variable.) Commented Sep 5, 2013 at 0:57

2 Answers 2

3
class A(object):

def __init__(self):
    self.a = 20

B = []
for i in range(10):
    B.append(A())

s = sum(i.a for i in B)

print s

works.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use reduce

reduce(lambda acc, c: acc + c, [i.a for i in B])

or sum() with comprehension

sum([i.a for i in B])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.