Search code examples
pythonlist-manipulation

In Python how to access elements of tuples using reduce()?


I want to add the numbers 1,2,3 from the below list of tuples together. I tried:

reduce(lambda (x,y),(z,t): y+t,[('a',1),('b',2),('c',3)])

I get an error:

TypeError: 'int' object is not iterable

How do I fix this error? Thank you


Solution

  • You are trying to add a list of tuples. Therefore your lambda must return a tuple (otherwise, how will you add one call's result to the next item?), and you must also use a starting value that is a tuple. Something like this works:

    reduce(lambda (x,y),(z,t): (0, y+t),[('a',1),('b',2),('c',3)], (0,0))[1]
    

    You end up with a tuple (0, 6) and then use [1] to just get the 6.

    If that looks ugly, it's because reduce is not a great tool for this. sum with a generator expression works much better:

    sum(x[1] for x in [('a',1),('b',2),('c',3)])