The Python Oracle

Multiple if statements in a lambda function

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Multiple If Statements In A Lambda Function
00:35 Accepted Answer Score 29
00:53 Answer 2 Score 21
01:08 Answer 3 Score 1
01:24 Thank you

--

Full question
https://stackoverflow.com/questions/3343...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #lambda

#avk47



ACCEPTED ANSWER

Score 29


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 stick to Adam Smith's approach. I find that easier to read.




ANSWER 2

Score 21


You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get to symbolize your final "else"

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



ANSWER 3

Score 1


This is one way where you can try multiple if else in lambda function

Example,

largest_num = lambda a,b,c : a if a>b and a>c else b if b>a and b>c else c if c>a and c>b else a

largest_num(3,8,14) will return 14