Search code examples
pythonlambdafunctional-programmingsum

Finding a sum in nested list using a lambda function


I have a data structure similar to this

table = [
    ("marley", "5"),
    ("bob", "99"),
    ("another name", "3")
]

What I would like to do, to get the sum of the 2nd column (5 + 99 + 3) functionally like this:

total = sum(table, lambda tup : int(tup[1]))

That would be similar syntax to the python function sorted, but that's not how you would use python's sum function.

What's the pythonic/functional way to sum up the second column?


Solution

  • One approach is to use a generator expression:

    total = sum(int(v) for name,v in table)