Advanced Topics in Python --Lambda Expressions


After several hours of trial and error/improvement, I got this code to work. This is not the classic code elsewhere. I am not sure why it works. Can someone be kind enough to explain why it works. Thank you.

message = filter(lambda n:n if n!="X" else " " ,garbled)
print message


filter() takes two arguments, a function and an iterable. The function is the anonymous lambda, and the iterable is the string, garbled.

The variable n in the lambda is a placeholder that acts like,

for n in sequence:

only in this case, the loop is run by filter as it iterates over garbled. The filter builds a new sequence based upon the result of the conditional expression of the lambda.

Your code is not quite right, though, since it looks similar to a list comprehension. We only need a conditional expression.

lambda n: n != 'X'

Give that a try and see if it is easier to visualize and understand.


Thank you for the quick response. The code did work and was accepted. I know it was/is not elegant .I don't understand why it worked.
For instance I don't understand this section of the code , n:n if n!="X" else "" ,garbled). why n : n.
Secondly, the conditional statement if n!="X". Is this saying if n is not equal to X is a false statement,we should return an empty space/remove "X"?
What is the second "n" doing. The code will not work without the second n nor will it work without ELSE.
Thanking you for your time



lambda n: n != 'X'

The first n is the parameter declaration, the second is the placeholder in the expression. filter manages the values (string characters) that are taken one at a time from garbled.

We only want values of n in the new list that meet the conditional. Any that don't are ignored. That is why we don't need if and else.


Thank you, that was useful. I have also tried your code and that works too. Cheers:grin:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.