1

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
1
  • 2
    sum([x[1] for x in a]) (you know there is a loop here, but you can't see it). Commented Mar 7, 2016 at 11:47

4 Answers 4

3

Without using loop you can use zip() function:

>>> 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.

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

Comments

3

Comprehensions:

a = [[1,2,3],[4,5,6],[7,8,9]]
print(sum(sublist[1] for sublist in a))

will result in

15

Comments

2

Use reduce so you dont create intermediate objects in memory:

>>>from functools import reduce
>>>reduce(lambda x, y: x + y[1], a, 0)
>>>15

Comments

1

All the other answers are totally fine, but here's a fourth way:

>>> import operator
>>> sum(map(operator.itemgetter(2), a))
15

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.