Search code examples
pythonlistpython-itertools

Add all Second Items of Each Sublist in List


So, I have a list with many sublists that looks something like this:

[[(1,2),1],[(5,2),3],[(4,0),2]]

And I would like Python to add together the second item in each list, so the 1, the 3, and the 2. I have been trying to find an itertools function for it, but I have had no success.


Solution

  • No need of itertools, just use sum with a generator expression:

    >>> lis = [[(1,2),1],[(5,2),3],[(4,0),2]]
    >>> sum(x[1] for x in lis)
    6