Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Lets say I have the following list:
a = [[1,2,3],[4,5,6],[7,8,9]]
Is there a way to sum all the seconds elements without using loop? Such as:
the_sum = 0 for num in a: the_sum += num[1] >>> 15
sum([x[1] for x in a])
Without using loop you can use zip() function:
zip()
>>> sum(list(zip(*a))[1]) 15
Note: If you are using python 2.X since zip returns a list instead of an iterator you don't need to use list() on zip function.
zip
list()
Add a comment
Comprehensions:
a = [[1,2,3],[4,5,6],[7,8,9]] print(sum(sublist[1] for sublist in a))
will result in
15
Use reduce so you dont create intermediate objects in memory:
>>>from functools import reduce >>>reduce(lambda x, y: x + y[1], a, 0) >>>15
All the other answers are totally fine, but here's a fourth way:
>>> import operator >>> sum(map(operator.itemgetter(2), a)) 15
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
sum([x[1] for x in a])(you know there is a loop here, but you can't see it).