pythonlambda

How to use lambda expressions inside append directly


Apply a lambda function while appending to a list pretty much asks exactly what I want, and the solution there is fine, but I wanted to know if there was a way to directly get the result of a lambda expression appended to a list like so:

mapset[ind].append(lambda x: str1[i] if str1[i] not in mapset[ind] else str2[i])

mapset is a list[list] while str1 and str2 are strings. Is there a way for me to get the result of this lambda expression instead of its reference appended to mapset? If so how?

I do not want to go:

f = lambda x:... 
mapset.append(f(i))

Solution

  • You are only defining the function, not actually calling it on i. i is the argument that will be bound to the parameter x (and used inside the function).

    mapset[ind].append((lambda x: str1[x] if str1[x] not in mapset[ind] else str2[x])(i))
    

    That said, you don't need a lambda expression at all; just use the body as the expression that gets evaluated to the argument to append.

    mapset[ind].append(str1[i] if str1[i] not in mapset[ind] else str2[i])
    

    I would also consider a few temporary variables to simplify the call to append:

    ms = mapset[ind]
    s1 = str1[i]
    s2 = str2[i]
    
    ms.append(s1 if s1 not in ms else s2)