Multiple if statements in lambda functions

I am trying to use 3 if expressions inside a python lambda function function. Here is my code:

y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' ' 

I was able to get two if statements to work very well, for example.

 x=lambda cake: "Yum" if cake=="chocolate" else "Yuck" 

Essentially, I want the lambda function to use if statements to return "X" if the character is True, "O" if it is false, and "otherwise." I'm not even sure that this is possible, but I could not find any information on the Internet, so I would really appreciate any help :)

+6
source share
2 answers

You are missing an else before 'O' . This works:

 y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' ' 

However, I think you should adhere to Adam Smith's approach. It’s easier for me to read.

+6
source

You can use an anonymous dict inside your anonymous function to verify this using the default dict.get to symbolize your final "else"

 y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ') 
+13
source

All Articles