-1

I want to sum all second members of a nested list's sub-lists,

such that :

list = [[an integer,integer to be added], [another integer, integer to be added], [...], [...], [...], [...],....]

I tried to use built-in functions like map or iteration.

timgeb
  • 76,762
  • 20
  • 123
  • 145

1 Answers1

2

I want to sum all second members of a nested list's sub-lists

Using sum and a simple generator comprehension will do.

>>> lst = [[1,2], [3,4]]
>>> sum(sublist[1] for sublist in lst)
6

To make it more understandable / add some explanation:

>>> [sublist[1] for sublist in lst]
[2, 4]

creates a list of all second elements for every sublist in your list. We pass that to the sum function (with the minor difference that we are actually passing a generator to save memory, but sum([sublist[1] for sublist in lst]) would work just fine as well).

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • By the way, [here](http://stackoverflow.com/questions/4799459/why-can-you-omit-the-surrounding-parentheses-for-generators-in-python-when-passi)'s why you can omit an extra set of parentheses when passing a generator to a function. – timgeb Jan 11 '16 at 01:55