Search code examples
pythonlambdareducefold

Python functools.reduce, how to reduce a list a return a new one


Answering a question I notice that I don't know how to return a list after doing append inside a reduce, for example

import functools

futures = [1,2,3]
records = functools.reduce((lambda res, future: res if (res.append(str(future))  == None) else res), futures, [])

I want the list ['1', '2', '3'], it is just a minimal example, because I want to do more than map values.

Is there a another way that this horrible if that I put inside the lambda?


Solution

  • You don't have to mutate the result list in your lambda; reduce takes the return value of the function as the result. So your lambda can be as simple as

    lambda res, future: res+[str(future)]