Search code examples
pythonlambdaflatmap

Flattening a list inside a lambda function


I am trying to construct a lambda expression which takes in tuples of the form: (a, b[], c), where b is a list of elements which needs to be flattened.

For example, the output of the expression should be: (a, b[0], c), (a, b[1], c), (a, b[2], c) ...

I've tried researching and looking for generator expressions that are similar to the situation I've just described, but I can't really wrap my head around this.

I would appreciate it if someone could point me in the right direction.


Solution

  • You can use itertools.repeat() with zip() to create the desired tuple for each element in b:

    from itertools import repeat
    
    f = lambda a, b, c: zip(repeat(a), b, repeat(c))
    
    print(*f(1, [2, 3, 4], 5))
    

    This outputs:

    (1, 2, 5) (1, 3, 5) (1, 4, 5)