Question

I have a function that returns a list, and I want to merge the outputs of that function when called on a list using a compact generator expression (or anything nice and compact)

Suppose I have a def foo(bar): where bar is in integer, and it returns a list after some crazy complex computation.

foo(1)=[9,1,5]
foo(2)=[1]
foo(3)=[7,1]

arr=[1,2,3]

How can I get arr=[9,1,5,1,7,1] hopefully after a single line of code?

arr=[foo(x) for x in arr] gives me [[9,1,5],[1],[7,1]]
And I'd hate to write another line to roll out the lists within the list.

Was it helpful?

Solution

from itertools import chain
result = list(chain.from_iterable(foo(x) for x in arr))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top